I have a text like bellow:
Ryan, Ryan needs to find his papers.
I want to change the pattern of
(sth), (sth)
to
(sth)
So, it doesn’t necessarily need to be Ryan, it could be any other name. And the output should look like this:
Ryan needs to find his papers.
So, basically this code but a variable instead of Ryan.
preg_replace("/(Ryan), (Ryan)/","/(Ryan)/",$text);
Advertisement
Answer
Use
preg_replace('/b(p{L}+)(?:,s*1)+b/u', '$1',$text)
See regex proof and PHP proof.
Explanation
--------------------------------------------------------------------------------
b the boundary between a word char (w) and
something that is not a word char
--------------------------------------------------------------------------------
( group and capture to 1:
--------------------------------------------------------------------------------
p{L}+ any character letter (1 or more
times (matching the most amount
possible))
--------------------------------------------------------------------------------
) end of 1
--------------------------------------------------------------------------------
(?: group, but do not capture (1 or more times
(matching the most amount possible)):
--------------------------------------------------------------------------------
, ','
--------------------------------------------------------------------------------
s* whitespace (n, r, t, f, and " ") (0
or more times (matching the most amount
possible))
--------------------------------------------------------------------------------
1 what was matched by capture 1
--------------------------------------------------------------------------------
)+ end of grouping
--------------------------------------------------------------------------------
b the boundary between a word char (w) and
something that is not a word char