How to get (in PHP) all substrings, which describes a regular expression?
I'm creating regular expression in the form: A | B | C ... automatically, by program, where A, B, C, ... are constant strings.
I need t开发者_如何学运维o find all the matches that correspond to these regular expression, even if the A, B, C, ... have not empty intersection, or someone is substring of other.
Example:
preg_match_all ('/Hello World|Hello|World lo/i', 'xxxHello worldxxx', $m, PREG_OFFSET_CAPTURE | PREG_SET_ORDER);
var_export ($m);
It gives:
array (
0 =>
array (
0 =>
array (
0 => 'Hello World'
1 => 3, // start of match
)
)
)
I would need:
array (
0 =>
array (
0 =>
array (
0 => 'Hello World'
1 => 3, // start of match
)
1 =>
array (
0 => 'Hello'
1 => 3, // start of match
)
2 =>
array (
0 => 'lo world'
1 => 6, // start of match
)
)
)
Is there any way to get it?
Thanks
Run a preg_match_all
for each expression.
I would use strpos:
$str = 'xxxHello worldxxx';
$arr = array('Hello World', 'Hello', 'World');
foreach($arr as $word) {
$pos = strpos(strtolower($str), strtolower($word));
echo "$word found at char $pos\n";
}
output:
Hello World found at char 3
Hello found at char 3
World found at char 9
精彩评论