0

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

3 Answers 3

3

You have to make your pattern non-greedy:

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

See this.

Sign up to request clarification or add additional context in comments.

Comments

2
$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

3 Comments

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
@Robert - you're better using Artefacto's example that makes the pattern ungreedy, rather than the ungreedy switch; but thanks anyway
my example is below, im not using greedy matching, (?<x>.*?)
0

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"
  }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.