PHP: How can I make preg_match match only the first occurrence?

三世轮回 提交于 2019-12-24 08:42:03

问题


preg_match($pattern, $subject, $matches), $matches seems to be an array of all matches, I only need the first occurrence of the regex pattern, and I want the matching to stop right away once it finds a match and store it in $matches. Is it possible? Thank you.

I'm not talking about greedy match(.* and .*?), an example is as follows,

$str = 'abcd,abed,abfd,abgd';
preg_match("/ab.d/", $str, $match);

I want it to find only abcd and not any of the further matches, for further matches are useless to me and I assume would take more time to process.


回答1:


I think you want like this:-

<?php
$str = 'abcd,abed,abfd,abgd';
if(preg_match("/ab.d/",$str ,$matches) !== false){ // check any match found or not
    echo "match found:".$matches[0]; // when found print that match
}//after printing execution will stops successfully.
?>

Output:- https://3v4l.org/bErZL




回答2:


preg_match does what you want - stops after first match, as opposed to preg_match_all, that finds all occurences. In your example:

$str = 'abcd,abed,abfd,abgd';
preg_match("/ab.d/", $str, $match);
echo $match[0];//abcd

If matches is provided, then it is filled with the results of search. $matches[0] will contain the text that matched the full pattern, $matches[1] will have the text that matched the first captured parenthesized subpattern, and so on.




回答3:


You could also go ahead and use T-Regx:

echo pattern('ab.d')->match('abcd,abed,abfd,abgd')->first(); //abcd


来源:https://stackoverflow.com/questions/30476674/php-how-can-i-make-preg-match-match-only-the-first-occurrence

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!