PHP RegEx / Substring从字符串中获取ID

时间:2011-07-14 07:34:03

标签: php

这是我的字符串:

**tag:my.domain.com,2011-07-13:/895645783/posts/NHg5XdqFb5b/**

我想采取最后一节 / NHg5XdqFb5b / 并删除斜杠。

也有任何工具可供attemtp使用吗?

3 个答案:

答案 0 :(得分:0)

您可以通过以下方式执行此操作:

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

或者如果你想使用正则表达式:(确保所有ID都是11个)

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

答案 1 :(得分:0)

你可以做一个preg_replace http://ch.php.net/preg_replace

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

答案 2 :(得分:0)

你可以使用explode,它将拆分字符串并返回一个数组

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

或者,

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

干杯,