views:

153

answers:

3

Hello all, I'm really confused as to using preg_replace but slowly learning.

I need help with the function:

$str= preg_replace('#\W\d+#', '\W \d+', $str);

The idea is that Im looking for numbers that have letters directly before them with no spaces,

ie abc123. (NOT 'abc 123' and NOT '123abc')

and how do I simply include a space or character in between so abc123 becomes abc 123 or abc@@123

thanks everyone!

+3  A: 

You want

$str= preg_replace('#([A-Za-z]+)(\d+)#', '$1 $2', $str);

\W doesn't do what you think it does; \w means "word character" and \W means "not word character". Since you specifically want letters, though, neither does what you want, and you need [A-Za-z], which is the character class matching all letters. You also need a + after it in order to match "one or more".

Parentheses are how you "capture" part of the expression for later reference; $1 and $2 refer to your parenthesis-captured text.

chaos
very good, works a treat. But for me I might actually need to check for brackets before the numbers too, so can the pattern do abc()123 as well?
bluedaniel
Make [A-Za-z] [A-Za-z()] and include any other characters inside, you may need to escape [ and ] if you do though.
meder
Thanks man that worked really well. Can't tell you what a help youve been
bluedaniel
+2  A: 
<?php

$str = 'abc()1234';
$str= preg_replace('#([a-zA-Z()])(\d+)#', '$1 $2', $str);

echo $str;

Output:

abc() 1234

$1 and $2 are backreferences and refer to the first and second captured groups, respectively. More info @ http://www.regular-expressions.info/brackets.html.

meder
I used preg_match in my example so you can actually see how the array is populated and what you can use for preg_replace. $1 and $2 would reference the first and second captured pieces, per chaos's example.
meder
Thanks for the help, can you help with my latest comment: 'very good, works a treat. But for me I might actually need to check for brackets before the numbers too, so can the pattern do abc()123 as well?'
bluedaniel
I updated it so it accounts for the ( and ).
meder
Thanks so much, Im gonna give you the right answer but you were both spot on.
bluedaniel
A: 

You can see the difference between /([A-Za-z])(\d+)/ and /([A-Za-z]+)(\d+)/ in the online PHP Regegular expressor tester. Both work with preg_replace in your case. But the latter also works with preg_match_all, so it's more robust.

unigg