PHP Questions Home | Register | Login
Categories
Arrays
Files
Forms
Creating PDFs
PHP Errors
Functions
Images
MySQL
Numbers
Others
Strings
Website
Unanswered

PHP Forums
Forums Index
MySQL Forum
PHP Forum
Flash/Actionscript
Javascript
Web design

More PHP
PHP Functions
Top Questions
Ask a Question
PHP Interview Questions
PHP Jobs
Ecommerce
IT Questions
Business Websites

Sponsors

sponsor ad
My Salary
PHP Developer Salary
Advertise Here

How do I replace a word in a string in PHP?


Manipulating strings and data is what the majority of PHP is about and what you will find yourself doing most - particularly if you use PHP on the web to process and manipulate user data entered into forms, for instance.

Therefore it is good to know how to replace a specific word or string within a string with something else.

Let's say, for instance, you want to remove swear words from a string of data. To make this example easy and show you how the function works, we're going to turn the word 'bloody' into 'b****y' in our example, so that it can be safely posted, say, on your message board:

<?php
//PHP program to clean swear words from data
$usersays "I hate this bloody film it's useless!";

$cleaned str_replace("bloody","b****y",$usersays);

echo 
"You wrote: $cleaned";
//You wrote: I hate this b****y film it's useless!
?>


If you had a whole list of words you wanted to substitute, then you could simply put them into an array and then loop around replacing each one in the input string.



Comment on this Question and Answer >>>

ASK A QUESTION

More strings PHP Questions

How do I format the output of a string?

How do I count how many times each character occurs in a string?

how to compare strings in PHP?

How do I find the position of a letter in a string in PHP?

How do I break email address into username and hostname?



Custom Search