Jose G. Garcia Jose G. Garcia - 8 months ago 28
PHP Question

Regex to get only characters without space inside special tags

I have 2 texts in a string:


%Juan Gonzalez%

And I want to only be able to get %Juan% and not the one with the Space, I have been trying several Regexes witout luck. I currently use:


but it gets both things, I tried adding and playing with [^\s] but it doesnt works.

Any help please?


The issue is that . matches any character but a newline. The /U ungreedy mode only makes .* lazy and it captures a text from the % up to the first % to the right of the first %.

If your strings contain one pair of %...%, you may use


See the regex demo

The \S+ pattern matches 1+ characters other than a whitespace, and the whole [^\h%] negated character class that matches any character but a horizontal space and % symbol.

If you have multiple %...% pairs, you may use


See another regex demo, where \h matches any horizontal whitespace.

PHP demo:

$re = '/%([^\h%]+)%/'; 
$str = "%Juan%\n%Juan Gonzalez%"; 
preg_match_all($re, $str, $matches);