Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace a single character within a match via Regex

Tags:

regex

I have a simple pattern that I am trying to do a find and replace on. It needs to replace all dashes with periods when they are surrounded by numbers.

Replace the period in these:

3-54
32-11
111-4523mhz

Like So:

3.54
32.11
111.4523mhz

However, I do not want to replace the dash inside anything like these:

Example-One
A-Test

I have tried using the following:

preg_replace('/[0-9](-)[0-9]/', '.', $string);

However, this will replace the entire match instead of just the middle. How do you only replace a portion of the match?

like image 474
Dave C Avatar asked May 17 '12 14:05

Dave C


1 Answers

preg_replace('/([0-9])-([0-9])/', '$1.$2', $string);

Should do the trick :)

Edit: some more explanation:

By using ( and ) in a regular expression, you create a group. That group can be used in the replacement. $1 get replaced with the first matched group, $2 gets replaced with the second matched group and so on.

That means that if you would (just for example) change '$1.$2' to '$2.$1', the operation would swap the two numbers. That isn't useful behavior in your case, but perhaps it helps you understand the principle better.

like image 119
soimon Avatar answered Nov 16 '22 07:11

soimon