I’m using regex in PHP. This is my script:
$s="2044 blablabla 2033 blablabla 2088";
echo preg_replace("/(20)\d\d/","$1 14",$s);
The result was like this:
20 14 blablabla 20 14 blablabla 20 14
I want to remove the space between the 20
and the 14
to get the result 2014
. How do I do that?
The metacharacter “\s” matches spaces and + indicates the occurrence of the spaces one or more times, therefore, the regular expression \S+ matches all the space characters (single or multiple). Therefore, to replace multiple spaces with a single space.
You can easily trim unnecessary whitespace from the start and the end of a string or the lines in a text file by doing a regex search-and-replace. Search for ^[ \t]+ and replace with nothing to delete leading whitespace (spaces and tabs).
Python String strip() function will remove leading and trailing whitespaces. If you want to remove only leading or trailing spaces, use lstrip() or rstrip() function instead.
Use JavaScript's string. replace() method with a regular expression to remove extra spaces. The dedicated RegEx to match any whitespace character is \s .
You need to use curly brackets inside single quotes:
echo preg_replace("/(20)\d\d/",'${1}14',$s);
After checking the preg_replace
manual:
When working with a replacement pattern where a backreference is immediately followed by another number (i.e.: placing a literal number immediately after a matched pattern), you cannot use the familiar
\\1
notation for your backreference.\\11
, for example, would confusepreg_replace()
since it does not know whether you want the\\1
backreference followed by a literal1
, or the\\11
backreference followed by nothing. In this case the solution is to use\${1}1
. This creates an isolated$1
backreference, leaving the1
as a literal.
Therefore, use
"\${1}14"
or
'${1}14'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With