How do I return a partial PHP string after a string match?

I want to return the page id from a URL string.

For example If I have this:

Read More
    <?php
    $string = "foobar.com/?page_id=20"; // <-dynamically generated

    $new_string = some_function($string, get stuff after 'page_id='); // (need to know what function to use and how)

    // I want to get this:
    echo $new_string; //($new_string = "20";)
?>

/// UPDATE!

I am attempting to add a class to a link if i am currently on that page or one of its children. Here is what I got:

<?php
$items = wp_get_nav_menu_items("navigation");
$counter = 1;
foreach($items as $item): ?>
<a id="mainnav<?php echo $counter; ?>" class="
<?php
//home
$theurl = $item->url;
$new_string = modify_withfunction("after page_id=", $theurl);

if ($new_string == $page->post_parent || $new_string == $page->ID) {
echo 'currentnav';
}
?>
" href="<?php echo $item->url; ?>"><?php echo $item->title; ?></a>
<?php 
$counter++;
endforeach;
?>

Related posts

Leave a Reply

4 comments

  1. You have two options. Extracting something out of a string is usually a task for regular expressions. They are easy when you realise you can just note a fixed string part, and one of the placeholders for what you want (d+ for decimals here):

    preg_match('/page_id=(d+)/', $str, $match);
    print $match[1];
    

    Or if it’s a URL string, then this is also possible:

    parse_str(substr(strrchr($str, "?"), 1), $params);
    print $params["page_id"];
    
  2. Untested, but this code should do:

    function get_pageid($str){
        preg_match("/page_id=(d+)?/", $str, $matches);
        return $matches[0];
    }
    

    But, that would only work of the ID you want to pull is a series of digits. You would need to modify the regular expression to match the format if it is different.

  3. since you have added wordpress tag to your question.

    wordpress offers $wp_query object and that object has a property called query_vars

    if(isset($wp_query->query_vars['page_id'])) {
        $page_id = urldecode($wp_query->query_vars['page_id']);
    }