PHP tutorial-Regular Expression


Regular Expression


In the previous part of this PHP tutorial, you learnt to do simple things to manipulate a string by using the PHP string manipulation functions. For complex string operatons, those functions are not useful. For example, If you want to replace any digit character in a string "PHP123JavaScript897C987" with "Programming, ". How can you do that? It is hard to accomplish this task.

For another example, if you want to allow a user to enter a phone number in the format: (855)987-678. It is also hard to complete this task by using what you have learnt with the string functions.


PHP provides preg_match() and preg_replace() functions that you can solve these such problems. By using a regular expression, you can define a complex pattern of string to be matched.
For example, to solve the first problem, you can write a string pattern as below:
$strpat='/\d+/';
Then supply this string variable to the preg_replace(pattern, replacement,string) function.
Example: <?php
$str="PHP123JavaScript897C987";
$strpat='/\d+/';
$strnew=preg_replace($strpat," Programming,",$str);
echo $strnew;
?>

A string pattern of regular expression is written between the forward slash(/pattern/) to inform the browsers that it is regular expression.
You may feel hard to write a pattern right now. In the next pages of Regular Expression topic you learn more things including how to write patterns and use them with the string manipulation functions mentioned previously.


Comments





This website intents to provide free and high quality tutorials, examples, exercises and solutions, questions and answers of programming and scripting languages:
C, C++, C#, Java, VB.NET, Python, VBA,PHP & Mysql, SQL, JSP, ASP.NET,HTML, CSS, JQuery, JavaScript and other applications such as MS Excel, MS Access, and MS Word. However, we don't guarantee all things of the web are accurate. If you find any error, please report it then we will take actions to correct it as soon as possible.