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
The str_replace() function replaces some characters with some other characters in a string. This function works by the following rules: If the string to be searched is an array, it returns an array. If the string to be searched is an array, find and replace is performed with every array element.
The Java string replace() method will replace a character or substring with another character or string. The syntax for the replace() method is string_name. replace(old_string, new_string) with old_string being the substring you'd like to replace and new_string being the substring that will take its place.
Approach 1: Using the str_replace() and str_split() functions in PHP. The str_replace() function is used to replace multiple characters in a string and it takes in three parameters. The first parameter is the array of characters to replace.
You can use strstr to do this. Show activity on this post. The explode is in fact a better answer, as the question was about removing the text before the string.
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)));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With