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