开发者

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:

    <?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
//h开发者_运维百科ome
$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;
?>


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"];


If you'd prefer not to use regular expressions.

You can look at:

  • parse_url
  • parse_str

Here's some example code:

<?php
parse_str(parse_url('foobar.com/?page_id=20', PHP_URL_QUERY));
var_dump($page_id);


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.


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']);
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜