Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I remove the space in the output of this regex? [duplicate]

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?

like image 424
ro0xandr Avatar asked Sep 12 '14 13:09

ro0xandr


People also ask

How do I remove double spacing in regex?

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.

How do you stop a space in regex?

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).

How do you remove spaces in Python output?

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.

How do you remove unwanted space from a string?

Use JavaScript's string. replace() method with a regular expression to remove extra spaces. The dedicated RegEx to match any whitespace character is \s .


2 Answers

You need to use curly brackets inside single quotes:

echo preg_replace("/(20)\d\d/",'${1}14',$s);
like image 112
Casimir et Hippolyte Avatar answered Sep 18 '22 14:09

Casimir et Hippolyte


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 confuse preg_replace() since it does not know whether you want the \\1 backreference followed by a literal 1, or the \\11 backreference followed by nothing. In this case the solution is to use \${1}1. This creates an isolated $1 backreference, leaving the 1 as a literal.

Therefore, use

"\${1}14"

or

'${1}14'
like image 28
hjpotter92 Avatar answered Sep 21 '22 14:09

hjpotter92