I have a text that has the possible values already in the text, i want to show the right values in situations. I’m not really good with regexes and i don’t really know how to explain my problem so here is an example. I’ve got it working almost:
$string = "This [was a|is the] test!";
preg_replace('/\[(.*)\|(.*)\]/', '$1', $string);
// results in "This was a text!"
preg_replace('/\[(.*)\|(.*)\]/', '$2', $string);
// results in "This is the test!"
This works without problems but when there are two parts it doesn’t work anymore because it gets the end bracket from the last.
$string = "This [was a|is the] so this is [bullshit|filler] text";
preg_replace('/\[(.*)\|(.*)\]/', '$1', $string);
//results in "This was a|is the] test so this is [bullshit text"
preg_replace('/\[(.*)\|(.*)\]/', '$2', $string);
//results in "This filler text"
Situation 1 should be the values between ( and | and situation 2 should show the values between | and ).
Your probem is the regex greediness. Add a
?after.*to make it consume only the string within the square brackets:Likewise could you use the
/Uungreedy modifier. Better yet use a more specific match in place of.*?anything.