views:

34

answers:

3

Hello all,

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 for 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

A: 

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"
  }
}
RobertPitt
+3  A: 

You have to make your pattern non-greedy:

/«(.*?)#(.*?)#(.*?)»/

See this.

Artefacto
+2  A: 
$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

Mark Baker
sorry, by bad, io copied your sample to save code writing and hit the downvote, gave you an upvote for the inconvenience and that your code is ok
RobertPitt
@Robert - you're better using Artefacto's example that makes the pattern ungreedy, rather than the ungreedy switch; but thanks anyway
Mark Baker
my example is below, im not using greedy matching, `(?<x>.*?)`
RobertPitt
Robert - ah, my bad!
Mark Baker