开发者

Find the last occurrence of "in" then capture the text there after

The bold text is what I'm trying to capture "the yard".

One boat in here. (in the yard)

One boat in here. in the yard

My regex capture开发者_运维知识库s "here. (in the yard", it gets caught on the first "in", but im trying to get it to only catch on the last appearance of "in".

My current regex is

\s\(?in([^\)]+)\)?$

If you know the solution please explain the regex, I would like to understand how it works.


\s Find a space
\(? Zero or one (i.e., optional) open parenthesis
in Literal i followed by literal n
[^\)]+ CAPTURE: One or more characters, none of which are ) (and maybe \ (not sure about this bit))
\)? Optional close parenthesis
$ End of line

This clearly matches the first string, with here. (in the yard being captured.

fix:

.*\s\(?in([^\)]+)\)?$

The .* causes the regex engine to first find the end of the string. It then backtracks from there to the last in.


Not sure what the Regex is for when you can use

$str = <<< TXT
One boat in here. (in the yard)
One boat in here. in the yard
TXT;

echo substr($str, strrpos($str, 'in') + 3); // 'the yard'

See

  • strrpos — Find the position of the last occurrence of a substring in a string
  • substr — Return part of a string

This does not obey word boundaries though. If you need word boundaries, Regex are indeed a better choice (or make the needle "in "). For a decent tutorial about Regex, see Perl's perlretut. Most, if not all, of that applies to PHP as well.


The regex is

/.*(?<=\bin\b)(?P<founded>.*?)$/
  • \b is a word boundary
  • (?<= ....) is a look behind.
  • $ is the end of the string
  • .* is greedy
  • .*? is ungreedy

So the full code is

<?php
$str = "I am in the backyard";
preg_match('/.*(?<=\bin\b)(?P<founded>.*?)$/', $str, $matches);
var_dump($matches['founded']);

// returns string(13) " the backyard"

Or simply

$str = "I am in the light in the backyard";
$matches = preg_split('/\bin\b/', $str);
var_dump(end($matches));

// returns string(13) " the backyard"
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜