[英]PHP preg_match starting from end of string
我正在嘗試捕獲字符串模式,但要從字符串的末尾開始。
如果我有一個像這樣的字符串:
"Hi, I saw you on tv yesterday. On Mon 4 P.M Alice wrote:"
捕獲單詞"on"
和單詞"wrote:"
之間的所有內容的常規preg_match
將捕獲"on tv yesterday. On Mon 4 PM Alice wrote:"
。 我要捕獲"On Mon 4 PM Alice wrote:"
。
我無法使用preg_match_all
解決它,因為它只會與第一個匹配。
我的模式:
/(<div>|<br>|<br \/>|<br\/>)\s*on\s(.*)wrote:/i
我也嘗試用strrpos
解決它,但是它不尊重空格。
謝謝馬丁
您可以將基於lookahead的正則表達式用於preg_match
輸入中的最后一個匹配項:
/\bon\b(?:(?!\bon\b).)*?\bwrote\b/i
(?:(?!\\bon\\b).)*?
為排除模式基於正則表達式將之間不匹配的文本on
,並wrote
,當on
沒有它們之間出現從而確保最后一場比賽中輸入相匹配 。
我認為最好的解決方案是使用我在這里找到的這些不錯的功能。 就我個人而言,我經常使用它,並且它從未讓我失望。
<?php
function strrevpos($instr, $needle)
{
$rev_pos = strpos (strrev($instr), strrev($needle));
if ($rev_pos===false) return false;
else return strlen($instr) - $rev_pos - strlen($needle);
};
function before ($this, $inthat)
{
return substr($inthat, 0, strpos($inthat, $this));
};
function between ($this, $that, $inthat)
{
return before ($that, after($this, $inthat));
};
?>
然后,您可以輕松地執行以下操作:
$string = 'Hi, I saw you on tv yesterday. On Mon 4 P.M Alice wrote:"';
$result = between ('On', 'wrote:', $string);
echo $result; //should echo "Mon 4 P.M Alice"
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.