提取字符串的最后一段


Extract last section of string

我有一个这样的字符串:

[numbers]firstword[numbers]mytargetstring

我想知道如何在考虑以下因素的情况下提取"targetstring":

a.)数字是数字,例如,我的完整数字字符串:

12firstword21mytargetstring

b.)数字可以是任何数字,例如上面的每个数字是两个数字,但它可以是任何数量的数字,如下所示:

123firstword21567mytargetstring

不管位数是多少,我只对提取"mytargetstring"感兴趣。

顺便说一句,"第一个词"是固定的,不会随着任何组合而改变。

我在Regex方面不是很好,所以我很感激有背景的人能建议如何使用PHP来做到这一点。非常感谢。

这将完成(或应该完成)

$input = '12firstword21mytargetstring';
preg_match('/'d+'w+'d+('w+)$/', $input, $matches);
echo $matches[1]; // mytargetstring

它分解为

'd+'w+'d+('w+)$

'd+-一个或多个数字

'w+-后面跟着一个或多个单词字符

'd+-后面跟着一个或多个数字

('w+)$-后面跟一个或多个结束字符串的单词字符。括号将其标记为要提取的组

preg_match("/[0-9]+[a-z]+[0-9]+([a-z]+)/i", $your_string, $matches);
print_r($matches);

您可以使用preg_match和模式语法来完成此操作。

$string ='2firstword21mytargetstring';
if (preg_match ('/'d('D*)$/', $string, $match)){
//                       ^ -- end of string
//                     ^   -- 0 or more
//                   ^^    -- any non digit character
//                ^^       -- any digit character                      
    var_dump($match[1]);}

试试吧,

print_r(preg_split('/'d+/i', "12firstword21mytargetstring"));
echo '<br/>';
echo 'Final string is: '.end(preg_split('/'d+/i', "12firstword21mytargetstring"));

测试日期http://writecodeonline.com/php/

您不需要正则表达式:

for ($i=strlen($string)-1; $i; $i--) {
   if (is_numeric($string[$i])) break; 
}
$extracted_string = substr($string, $i+1);

在上面,它可能是您可以获得的更快的实现,当然比使用regex更快,在这种简单的情况下您不需要regex。

请参阅工作演示

您的简单解决方案如下:-

$keywords = preg_split("/['d,]+/", "hypertext123language2434programming");
echo($keywords[2]);