Traverse string and replace a specific PHP character

Asked

Viewed 41,918 times

7

I wanted to replace, in a string, all character occurrences & by a e (or remove it). The character may be in the middle of a word or appear several times in the same string.

Example:

Original value: João went to the Hotel & Spa for holidays.

After replacement: João went to the Hotel and Spa to spend holidays.

  • And either the result corrected in a variable or you want to replace in the database?

  • @Sergio I want the result in a variable

1 answer

20


You can use the str_replace(), the parameters of this function are:

str_replace(search, substitute, source, $occurrences)

seek out - the text to search for
substitute - the text that should replace what is found in seek out
origin - the string where the contents are to be replaced
$occurrences (optional) - this variable will receive the value of how many times replace was executed and the text found/replaced.

An example would be:

$string = "O João foi ao Hotel & Spa passar férias";
$stringCorrigida = str_replace('&', 'e', $string);
echo $stringCorrigida; // resultado: O João foi ao Hotel e Spa passar férias
  • That’s right. Thank you @Sergio

  • @pc_oc great. I’m glad I helped.

  • How strange that this solution does not apply to this question: http://answall.com/questions/54541/comor-posso-converter-estas-strings-no-php ... will it be because str_replace is having problems with the characters?

  • Sergio, and in case the occurrence is any value inside an array? How to do this?

  • @Dichrist can give an example?

  • Yes. For example, if in a text I have several occurrences of the <br /> tag, and I want to make sure that if in that text you have 3 or more <br /> tags in a row are replaced by a single one, I wouldn’t have to use the array to save those occurrences and use that array in replace?

  • 1

    @Dichrist think it would be better to ask a separate question, in which case I think the best would be CSS.

Show 2 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.