Jump to content

str_replace Question


JSHINER

Recommended Posts

I currently have:

 

str_replace('-', '', trim($row[5]));

 

Which makes a phone number of 555-555-5555 display as 5555555555.

 

How can I also have it replace . so 555.555.555 will display as 5555555555 also.

 

 

Thanks

Link to comment
Share on other sites

Just replace the "-" with a "." in your str_replace() function. If you want to replace any occurrence of "-" or "." in the string use an array:

<?php
$str = array();
$str[] = '555-555-5555';
$str[] = '555.555.5555';
$str[] = '555.555-5555';
for ($i=0;$i<count($str);$i++)
     echo 'Before: ' . $str[$i]. ' ===> After: ' . str_replace(array('-','.'),'',$str[$i]) . '<br>';
?>

 

Ken

 

Link to comment
Share on other sites

I am using the code to import from a .csv to a sql database. So I need it to take the data from $row[5] and manipulate that... and create a final variable to import... example now I have:

 

$phone = str_replace('-', '', trim($row[4]));

 

I need it to replace - in a phone number or . in a phone number - however they are formatted.

 

From what I uderstand - will this work?

 

$phone = str_replace(('-','.'), '', trim($row[4]));

 

 

Link to comment
Share on other sites

Try it ;)

I think for you it's the best way to use it like that:

<?php
   $phone = '555.555-555.555-55';
   $phone = str_replace('-', '', $phone);
   $phone = str_replace('.', '', $phone);
   echo $phone;
?>

Link to comment
Share on other sites

I am not sure if str_replace has this functionality, but ereg_replace works too. Most people shy away from it because it takes "longer" to process, but really unless you are running this 5,000 times you should not see a difference.

 

<?php
   $phone = '555.555-555.555-55';
   $phone = ereg_replace('-|.', '', $phone);
   echo $phone;
?>

 

Now I cannot remember if the "." is a special character if so do this:

 

   $phone = ereg_replace('-|\.', '', $phone);

 

That should work how you want it.

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.