How do I replace part of a string in PHP?

Php

Php Problem Overview


I am trying to get the first 10 characters of a string and want to replace space with '_'.

I have

  $text = substr($text, 0, 10);
  $text = strtolower($text);

But I am not sure what to do next.

I want the string

> this is the test for string.

become

> this_is_th

Php Solutions


Solution 1 - Php

Simply use str_replace:

$text = str_replace(' ', '_', $text);

You would do this after your previous substr and strtolower calls, like so:

$text = substr($text,0,10);
$text = strtolower($text);
$text = str_replace(' ', '_', $text);

If you want to get fancy, though, you can do it in one line:

$text = strtolower(str_replace(' ', '_', substr($text, 0, 10)));

Solution 2 - Php

You can try

$string = "this is the test for string." ;
$string = str_replace(' ', '_', $string);
$string = substr($string,0,10);

var_dump($string);

Output

this_is_th

Solution 3 - Php

This is probably what you need:

$text = str_replace(' ', '_', substr($text, 0, 10));

Solution 4 - Php

Just do:

$text = str_replace(' ', '_', $text)

Solution 5 - Php

You need first to cut the string in how many pieces you want. Then replace the part that you want:

 $text = 'this is the test for string.';
 $text = substr($text, 0, 10);
 echo $text = str_replace(" ", "_", $text);

This will output:

> this_is_th

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionRougeView Question on Stackoverflow
Solution 1 - PhpJonah BishopView Answer on Stackoverflow
Solution 2 - PhpBabaView Answer on Stackoverflow
Solution 3 - PhpZathrus WriterView Answer on Stackoverflow
Solution 4 - PhpNelsonView Answer on Stackoverflow
Solution 5 - PhpicemanView Answer on Stackoverflow