Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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

like image 680
Rouge Avatar asked Sep 26 '12 15:09

Rouge


People also ask

How can I replace part of a string in PHP?

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.

How do you replace a specific part of a string?

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.

How can I replace multiple characters in a string in PHP?

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.

How do you remove portion of a string before a certain character in PHP?

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.


1 Answers

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))); 
like image 193
Jonah Bishop Avatar answered Sep 24 '22 15:09

Jonah Bishop