[php] How do I replace part of a string in PHP?

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

This question is related to php

The answer is


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

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


This is probably what you need:

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

Just do:

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