如何在 php 中从后搜索字符串


How to search a string from backwards in php?

$str="This is a string with <xref cite@#>test</xref> and 
<xref cite@#>string2</xref>";

我需要获取"@#>test"和"xref"之间的字符串。

我试过了:

$start=strpos($str,"@#>test");
$end=strpos($str,"xref ",$start); //here how to search backwards from  "@#>test"
//to "xref "

预期产出:引用

strpos - 仅用于获取字符串的最后出现次数。是否有任何功能可以从指定的位置向后搜索字符串?

试试这个:通过正则表达式(?<=xref).*(?=@#)

$re = "/(?<=xref).*(?=@#)/m";
$str = "This is a string with <xref cite@#>test</xref> and 'n<xref cite@#>test</xref>";
preg_match_all($re, $str, $matches);
[

现场演示][1]

更新:(?<=<xref).*?(?=@#)

$re = "/(?<=<xref).*?(?=@#)/m";
$str = "This is a string with <xref cite@#>test2</xref> and <xref cite@#>test1</xref><xref cite@#>test</xref><xref cite@#>test1</xref>'n<xref cite<e.g.>[p.11]@#>test</xref>";
preg_match_all($re, $str, $matches);

更新链接

没有从指定位置向后搜索的功能,但一个简单的解决方法是仅使用 substr 截断所需位置的输入,然后使用 strrpos

$truncated = substr($str, 0, $start);
$end = strrpos($truncated, "xref ");

但是,对于这种不太简单的模式匹配,正则表达式似乎可能是一个更方便的选择。

http://php.net/manual/en/function.strrpos.php

如果该值为负数,则搜索将从字符串末尾的那么多字符开始,向后搜索。

因此,如果为偏移量提供负数,则可以向后搜索。这应该有效

$end=strpos($str,"@#>test");
$start=strpos($str,"xref ",$end-strlen($str)); 
$output=substr($str,$start, $end-$start);