preg_replace() string pattern search and replacment

$string=" Welcome to html  & HTML section";
echo $string;
Welcome to MySQL & HTML section


Search_string:Enter the pattern of search string. This can be an array.
replace_string: If search string is found then this string ( replace_string ) is to be replaced.
main_string:This is our main string on which search will applied and replaced with replace string.
Limit :(optional ) We can specify how many times or occurrence of search to be replaced. It can be set to -1 for unlimited search and replace.
Count: ( optional )Returns the variable storing number of times search and replace is used within the string.


$string=" Welcome to , you can read html, php , jquery & HTML here";
echo $string;
Output is here
Welcome to , you can read MySQL, php , jquery & HTML here
Note that we could change only html , not HTML . This is a case sensitive search and replace. To make it case in sensitive we have to add one i after the string delimiters.
Now it is not case sensitive and both occurrence of the string HTML & html will be replaced with MySQL


To mark the starting and ending of the string we have used delimiters, in above case we used / as delimiters. However we can use any non-alphanumeric, non-backslash, non-whitespace character. Here is a list of commonly used delimiters to create patterns for searching.

Forward slash / , hash sign #, tildes ~

Counting Number of Replacements

We have one optional count variable which stores the number of replacements done by preg_replace().
$string=" Welcome to , you can read html, php , jquery & HTML here";
echo $string;
echo "<br>Total replacement done : $count ";
Output is here
Welcome to , you can read MySQL, php , jquery & MySQL here
Total replacement done : 2
If you are dynamically building a query by taking different conditions connected by AND operator then this code is useful as you can replace the first occurrence of AND with a WHERE to complete your query.

String Functions ucfirst(): First char to upper case str_replace(): String replace Counting Sub string inside a string
Subscribe to our YouTube Channel here


* indicates required
Subscribe to plus2net

    Post your comments , suggestion , error , requirements etc here

    PHP video Tutorials
    We use cookies to improve your browsing experience. . Learn more
    HTML MySQL PHP JavaScript ASP Photoshop Articles FORUM . Contact us
    ©2000-2024 All rights reserved worldwide Privacy Policy Disclaimer