The question itself is pretty self explanatory. But I want to clear up something: I'm not asking for a regex which does not match if the number of matches is odd/even. I'm asking for a regex that excludes all odd/even matches.
Also, here's my regex which should work in the solution : (?<=\*)[^*]*(?=\*)
The final goal is to replace the leading and trailing asterisks without modifying or losing the strings between the asterisks.
CodePudding user response:
This issue occurs because the asterisks on both ends of the matches need to be consumed, else, the trailing asterisk will become the next match start position.
You need to consume these strings while capturing the data between the two asterisks, then obtain the Group 1 values:
if (preg_match_all('~\*([^*]*)\*~', $text, $matches)) {
print_r($matches[1]);
}
See the PHP demo.
To replace the asterisks only, without touching the content in between, you can use
$text = 'Abc *def* ghi *jkl*';
echo preg_replace('~\*([^*]*)\*~', '<b>$1</b>', $text);
// => Abc <b>def</b> ghi <b>jkl</b>
See this PHP demo.