Jose G. Garcia Jose G. Garcia - 5 months ago 15
PHP Question

Regex to get only characters without space inside special tags

I have 2 texts in a string:

%Juan%

%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:

/%(.*)%/U


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

Any help please?

Answer

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

/%(\S+)%/

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

/%([^\h%]+)%/

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);
print_r($matches[1]);