How do you do a regex in php that finds a space that has a letter on its left and a number on its right?
I have done many of these over the last day and at best I can find the “letter space number” combo, but I do not know how to find just the space between the letter and number. I would like to replace this space with a comma.
E.G:
The big red Fox 283 brown balls
would be converted to:
The big red Fox,283 brown balls
Thank you in advance for answering this question. If you provide an explanation with how the answer works it would be greatly appreciated.
You can use the preg_replace function to do this:
The
[a-zA-Z]part of the regex matches any letter, and the[0-9]matches any digit. Together,/[a-zA-Z] [0-9]/means that we want to match any letter followed by a space, followed by a digit.The circle brackets denote backreferences, which allows parts of the original string to be “remembered” (in the variables
$1and$2) so that we can include those matched strings in the replacement string.