Open In App

How to convert ereg expressions to preg in PHP ?

A regular expression is a specially formatted pattern that can be employed to find the instance of one string within another. There are various ways by which we can equip regular expressions to meet the requirement.

ereg() function: The new versions of PHP don’t support ereg anymore, so the outputs are given using the video when tried on an old version. One way being the use of ereg() function.



Examples: 

Input: echo ereg("[a-zA-Z]","jack"); 
Output: 1
Input: echo ereg("^j","jack");
Output: 1

preg() function: Another way of checking for regular expressions is by using preg() function. To use preg in your program it is advised to create a regex variable to compare with the subject. The following example provides the same functionality as the above code but by using preg. 



Examples:  

Input:  
$regex='/[a-zA-Z]/';
echo preg_match($regex,'jack');
Output:1
Input: 
$regex='/^[j]/';
echo preg_match($regex,"jack");
Output: 1

Convert ereg expressions to preg: The above information depicts how ereg and preg work separately. The ereg and preg are generally worked the same but have a slight difference in the way they are employed. Now the answer to the question “how can you convert ereg to preg” is given below. The following steps can convert any ereg to preg.  

Example: This example implements how to convert ereg expressions to preg. 




<?php
function pregcheck($num) {
    $regex='/[0-9]/';
    return preg_match($regex,$num);
}
 
function eregcheck($num) {
    return ereg("[0-9]",$num);
}
 
$abc = "123";
echo "pregcheck at work : ";
echo pregcheck($abc);
 
echo " eregcheck at work : ";
echo eregcheck($abc);
?>

Output: 

pregcheck at work : 1 eregcheck at work : 1 

 

Article Tags :