Converting Javascript Regex to PHP

前端 未结 2 1112
心在旅途
心在旅途 2020-12-20 19:17

I know this question has been asked about a dozen times, but this one is not technically a dupe (check the others if you like) ;)

Basically, I have a Javascript rege

2条回答
  •  被撕碎了的回忆
    2020-12-20 19:43

    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.

提交回复
热议问题