I have a string with some codes (ex:«USER_ID#USERNAME#STATUS») for replacement like in this example:
Hello «USER_ID#USERNAME#STATUS», do you like «PROD_ID#PRODNAME#STATUS»?
I need to find a way to get all the codes f开发者_开发问答or future replacement.
I can easily find one code with this regex:
/«(.*)#(.*)#(.*)»/
but can't find a way to get all the codes with preg_match_all.
Can someone help me? I'm using PHP.
Thanks
You have to make your pattern non-greedy:
/«(.*?)#(.*?)#(.*?)»/
See this.
$string = "Hello «USER_ID#USERNAME#STATUS», do you like «PROD_ID#PRODNAME#STATUS»?";
preg_match_all('/«(.*)#(.*)#(.*)»/U',$string,$matches);
echo '<pre>';
var_dump($matches);
echo '</pre>';
gives
array(4) {
[0]=>
array(2) {
[0]=>
string(25) "«USER_ID#USERNAME#STATUS»"
[1]=>
string(25) "«PROD_ID#PRODNAME#STATUS»"
}
[1]=>
array(2) {
[0]=>
string(7) "USER_ID"
[1]=>
string(7) "PROD_ID"
}
[2]=>
array(2) {
[0]=>
string(8) "USERNAME"
[1]=>
string(8) "PRODNAME"
}
[3]=>
array(2) {
[0]=>
string(6) "STATUS"
[1]=>
string(6) "STATUS"
}
}
Note the use of the Ungreedy switch.
I'm sure somebody will be along soon to modify the regexp so that it's inherently ungreedy
try
preg_match_all('/«(?<id>.*?)#(?<username>.*?)#(?<status>.*?)»/',$string,$matches);
echo $matches[0]['username'];
//And dont forget you have to loop.
foreach($matches as $match)
{
echo $match['username'];
}
:)
array(7) {
[0]=>
array(2) {
[0]=>
string(27) "«USER_ID#USERNAME#STATUS»"
[1]=>
string(27) "«PROD_ID#PRODNAME#STATUS»"
}
["id"]=>
array(2) {
[0]=>
string(7) "USER_ID"
[1]=>
string(7) "PROD_ID"
}
[1]=>
array(2) {
[0]=>
string(7) "USER_ID"
[1]=>
string(7) "PROD_ID"
}
["username"]=>
array(2) {
[0]=>
string(8) "USERNAME"
[1]=>
string(8) "PRODNAME"
}
[2]=>
array(2) {
[0]=>
string(8) "USERNAME"
[1]=>
string(8) "PRODNAME"
}
["status"]=>
array(2) {
[0]=>
string(6) "STATUS"
[1]=>
string(6) "STATUS"
}
[3]=>
array(2) {
[0]=>
string(6) "STATUS"
[1]=>
string(6) "STATUS"
}
}
精彩评论