91

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

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Rouge
  • 4,181
  • 9
  • 28
  • 36

5 Answers5

170

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)));
Jonah Bishop
  • 12,279
  • 6
  • 49
  • 74
  • 3
    I find the "fancy" version easier to read. It's worth noting that the order of `strtolower` and `str_replace` doesn't matter unless the replacement strings depend on lowercase or uppercase characters. – Pharap Aug 03 '18 at 17:55
8

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
Baba
  • 94,024
  • 28
  • 166
  • 217
5

This is probably what you need:

$text = str_replace(' ', '_', substr($text, 0, 10));
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Zathrus Writer
  • 4,311
  • 5
  • 27
  • 50
4

Just do:

$text = str_replace(' ', '_', $text)
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Nelson
  • 49,283
  • 8
  • 68
  • 81
2

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

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
iceman
  • 97
  • 7