Regular Expression With JS and PHP
Regular Expression With JS and PHP
Regular Expression With JS and PHP
Weimao Ke
Regular Expressions (RegEx)
Regular Expressions (RegEx)
A regular expression is
a sequence of symbols that forms a search pattern.
I Symbols include alphabets, numbers, and special characters.
I They can be used for text search/matching, or search &
replace.
Basic Syntax
Basic Syntax
/pattern/modifiers
Example:
/CCI/i
I This will match the string containing CCI
I i modifier for case-insensitive, i.e. cci matches
Javascript Regular Expression
Javascript Regular Expression
For example, the following will search for CCI in a URL string:
var myURL = "https://cci.drexel.edu";
var position = myURL.search(/CCI/i);
if(position>=0){
console.log("Found CCI at position " + position);
}else{
console.log("URL does not contain CCI");
}
Replace
$myURL = "https://cci.drexel.edu";
$pattern = "/CCI/i";
echo preg_match($pattern, $myURL); // output 1 as there is
Replace
$oldURL = "https://ischool.drexel.edu";
$pattern = "/iSchool/i";
$newURL = preg_replace($pattern, "cci", $oldURL);
echo $newURL;
References
References
I https://www.w3schools.com/js/js_regexp.asp
I https://www.w3schools.com/jsref/jsref_obj_regexp.asp
I https://www.w3schools.com/php/php_regex.asp