1

I have an array which contain strings and some of that string contains dots ( '.' ).

And I must repeat. I don't want to do this with str_replace.

So, I need to replace that dots with underscores.

For example:

for($data as $key=>$value){
   print_r($value);
}

Lets say how output is:

'Hello. I have two dots. Please replace them!'

And what would like we to have is:

'Hello_ I have two dots_ Please replace them!'

Thanks in advance

3
  • Use preg_replace instead ? Apr 11, 2014 at 7:59
  • preg_replace('/\./', '_', $value); but why not str_replace()?
    – dikesh
    Apr 11, 2014 at 8:05
  • 2
    @ShankarDamodaran to me it looks like a school work assignment. maybe teacher want them to treat strings like char arrays or something. i just posted a solution if thats the case.
    – Sharky
    Apr 11, 2014 at 8:07

6 Answers 6

9

is this a codegolf or something?

anyway here's a solution:

$text='Hello. I have two dots. Please replace them!';

echo IHateStrReplace(".","_",$text);

function IHateStrReplace($replace_from,$replace_to,$input)
{
    $result="";

    for($i=0;$i<strlen($input);$i++)
    {
        $result.= ($input[$i]==$replace_from)?$replace_to:$input[$i];
    }

    return $result;
} 

http://3v4l.org/Cjp4G

2
  • Voted up for the function name IHateStrReplace :) Apr 11, 2014 at 8:09
  • Likewise. preg_replace aside, this is the best answer.
    – Helpful
    Apr 11, 2014 at 8:13
3

How about

$original_string = 'Hello. I have two dots. Please replace them!';
$exploded_string = explode('.' , $original_string);
$new_string = implode('_' , $exploded_string);
2
echo strtr('Hello. I have two dots. Please replace them!', '.', '_');

String Translate does a byte-by-byte translation of the string.

0

You can use preg_replace. https://www.php.net/preg_replace

$var = 'Hello. I have two dots. Please replace them!';
echo preg_replace('#\.#', '_', $var);
0

Regex is overkill for replacing a single character but if you have to avoid str_replace() then this will do it:

foreach($data as $key => $value){
    $data[$key] = preg_replace('/\./', '_', $value);
}

print_r($data);
0

For future searchers, strtr() (string translate) translates single characters, so combining it with array_map makes for a neat solution:

// Push every item in the array through strtr()
$array = array_map('strtr', $array, ['.', '_']);

However, in benchmarking I've found strtr() to be slower than str_replace(), so I tend to use that instead.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.