开发者

PHP RegEx/Substring to get ID from a string

Here is my string:

**tag:my.domain.com,2011-07-13:/895645783/posts/NHg开发者_JS百科5XdqFb5b/**

I want to take the last section /NHg5XdqFb5b/ and remove the slashes.

Also are there any tools available to attemtp to work this out?


You can do this by:

<?php
    $id = explode("/", "**tag:my.domain.com,2011-07-13:/895645783/posts/NHg5XdqFb5b/**");
    $myID = $id[count($id)-2]; 
?>

Or if you want to use regex: (make sure all ids are 11 in length)

preg_match("/[a-zA-Z0-9]{11}/i", "**tag:my.domain.com,2011-07-13:/895645783/posts/NHg5XdqFb5b/**", $matches);
echo($matches[0]);


You could do a preg_replace http://ch.php.net/preg_replace

$var = preg_replace('~.*/([^/]+)/\*\*~','$1',$var);


You can use explode, which will split the string and return an array

$arr = explode("/", your_string_here); //split string by "/"
$id = $arr[count($arr) - 2]; //in your case, get the second-last part

Alternatively,

$arr = preg_match("\/posts\/(.*?)\/", your_string_here); //matches /posts/NHg5XdqFb5b/
//$arr[0] = whole match
//$arr[1] = 1st capture group (part between brackets) in your regex, i.e. required id
$id = $arr[1];

Cheers,

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜