[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.



This question is related to php

The answer is

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)));

Similar questions with php tag: