Jump to content

preg_replace Any Number Space Any Number


Failing_Solutions

Recommended Posts

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.

 

 

Link to comment
Share on other sites

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

Link to comment
Share on other sites

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)

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.