preg_match returns identical elements only once
I am going through a string and proces all the elements between !-- and --!. But only unique elements are processes. When I have !--example--! and a bit further in the text also !--开发者_开发技巧example--!, the second one is ignored.
This is the code:
while ($do = preg_match("/!--(.*?)--!/", $formtext, $matches)){
I know about preg_match_all, but need to do this with preg_match.
Any help? Thanks in advance!
You'll want PHP to look for matches only after the previous match. For that, you'll need to capture string offsets using the PREG_OFFSET_CAPTURE flag.
Example:
$offset = 0;
while (preg_match("/!--(.*?)--!/", $formtext, $match, PREG_OFFSET_CAPTURE, $offset))
{
// calculate next offset
$offset = $match[0][1] + strlen($match[0][0]);
// the parenthesis text is accessed like this:
$paren = $match[1][0];
}
See the preg_match documentation for more info.
Use preg_match_all
edit: some clarification yields:
$string = '!--example--! asdasd !--example--!';
//either this:
$array = preg_split("/!--(.*?)--!/",$string,-1,PREG_SPLIT_DELIM_CAPTURE);
var_dump($array);
array(5) {
[0]=>
string(0) ""
[1]=>
string(7) "example"
[2]=>
string(10) " asdasd "
[3]=>
string(7) "example"
[4]=>
string(0) ""
}
//or this:
$array = preg_split("/(!--(.*?)--!)/",$string,-1,PREG_SPLIT_DELIM_CAPTURE);
var_dump($array);
array(7) {
[0]=>
string(0) ""
[1]=>
string(13) "!--example--!"
[2]=>
string(7) "example"
[3]=>
string(10) " asdasd "
[4]=>
string(13) "!--example--!"
[5]=>
string(7) "example"
[6]=>
string(0) ""
}
while ($do = preg_match("/[!--(.*?)--!]*/", $formtext, $matches)){
Specify the * at the end of the pattern to specify more than one. They should both get added to your $matches array.
精彩评论