Converting Javascript Regex to PHP

There are some differences between regex engines in Javascript and PHP. Please check Comparison of regular-expression engines
article for theoretical and Difference between PHP regex and JavaScript regex answer for practical information.

Most of the time, you can use Javascript regex patterns in PHP with small modifications. As a fundamental difference, PHP regex is defined as a string (or in a string) like this:

preg_match('/^\(?(\d{3})\)?[- ]?(\d{3})[- ]?(\d{4})$/',$telephone);

Javascript regex is not, it’s defined in its own way:

var ptr = new RegExp(/^\(?(\d{3})\)?[- ]?(\d{3})[- ]?(\d{4})$/);
// or
var ptr = /^\(?(\d{3})\)?[- ]?(\d{3})[- ]?(\d{4})$/;

You can give it a try by running the regex on PHP. As a recommendation, do not replace it in Codeigniter files, you can simply extend or replace native library. You can check Creating Libraries out for more information.

Leave a Comment