Jump to content

preg_replace Any Number Space Any Number


Failing_Solutions

Recommended Posts

Hi folks,

 

I'm trying to use php to replace Number-Space-Number with Number-Comma-Number

Example

7 1036551

Would be

7,1036551

 

I've tried

$numbers='/([0-9]) ([0-9])/';
$replacement =',';
$str=preg_replace($numbers,$replacement,$str);

But no luck..

Any help is appreciated

Thank you

 

Thanks for the reply requinix but still not getting the results

$numbers='/([0-9]) ([0-9])/';
$replacement ='$1,$2';
$str=preg_replace($numbers,$replacement,$str);

 

 

My results are still showing

Array ( [0] => 1036550 [1] => Chronomancer [2] => 1 [3] => Very Long [4] => Crucias [5] => 7 1036551 [6] => Chronomancer [7] => 1 [8] => Very Long [9] => Crucias [10] => 7 1036553)

 

Think something is wrong with my $numbers variable..

 

Just trying to add that comma in there so I can explode it correctly on commas.

 

 

humm good point didn't think of that

 

$numbers='/([0-9])\s+([0-9])/';

 

Fixed it, thank you very much.

 

Also I did have a question on how / why $1, $2 works in the replacements. Are those some sort of automatically derived variables? If looking for like 3 numbers 121 222 333 would the third number replaced automatically be $3?

 

Just want to understand it,

 

Thanks again

Not sure what you mean, but $number comes from the matched groups in the search expression - the ones you put ()s around. If you had

/([0-9])\s+([0-9])([0-9])/

(which is inefficient but suitable for this example) then $1=the digit before the space, $2=the digit immediately after, and $3=the digit immediately after that. \1, \2, and \3 also work.

 

If you wanted groups of numbers then you'd have to change the expression a little: it only matches individual digits right now.

/(\d+)\s+(\d+)\s+(\d+)/

with \d being shorthand for [0-9] and + meaning "at least one of", then $1-3 are the first through third numbers. Then you'd replace it with

$1,$2,$3

(or \1,\2,\3)

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.