Can I use javascript regex in php as it

I am using regex in javascript and want to perform server side validation as well with the same regex. I need to change it to make it compatible or it will start as it is.

How to use regex php. Give a small example.

Thanks at Advance

EDIT

To check email

var pattern = new RegExp(/^(("[\w-\s]+")|([\w-]+(?:\.[\w-]+)*)|("[\w-\s]+")([\w-]+(?:\.[\w-]+)*))(@((?:[\w-]+\.)*\w[\w-]{0,66})\.([az]{2,6}(?:\.[az]{2})?)$)|(@\[?((25[0-5]\.|2[0-4][0-9]\.|1[0-9]{2}\.|[0-9]{1,2}\.))((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.){2}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\]?$)/i); 

To confirm the phone number

 var pattern = new RegExp(/^\(?(\d{3})\)?[- ]?(\d{3})[- ]?(\d{4})$/); 
+4
source share
4 answers

You must use one of the following preg_match or preg_match_all functions. And with little luck, you do not need to change your regular expression. PHP regex uses the classic Perl regular expression, so the match will look like this: preg_match_all('/([a-zA-Z0-9]+)/', $myStringToBeTested, $results);

Next edit:

 $string=" test@mail.com "; if(preg_match('/^(("[\w-\s]+")|([\w-]+(?:\.[\w-]+)*)|("[\w-\s]+")([\w-]+(?:\.[\w-]+)*))(@((?:[\w-]+\.)*\w[\w-]{0,66})\.([az]{2,6}(?:\.[az]{2})?)$)|(@\[?((25[0-5]\.|2[0-4][0-9]\.|1[0-9]{2}\.|[0-9]{1,2}\.))((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.){2}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\]?$)/', $string)) echo "matches!"; else echo "doesn't match!"; 

Enjoy it!

+2
source

It is supposed to work for most templates, except for the exception of special characters and backslashes, but not the opposite, the php-regular expression has functions other than javascript, for example, appearance expressions.

 javascript : /[az]+/ php : '/[az]+/' 

For instance,

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

will be '/^\(?(\d{3})\)?[- ]?(\d{3})[- ]?(\d{4})$/' in php

+3
source

PHP regexp is based on PCRE (Perl Compatible Regular Expression). Example (find numbers):

 preg_match('/^[0-9]*$/', 'my01string'); 

See php documentation .

Javascript regex is slightly different (ECMA).

 var patt1 = new RegExp("e"); document.write(patt1.test("The best things in life are free")); 

See here for a comparison table.

+3
source

In PHP, we use the preg_match function.

 $email_pattern = '/^(("[\w-\s]+")|([\w-]+(?:\.[\w-]+)*)|("[\w-\s]+")([\w-]+(?:\.[\w-]+)*))(@((?:[\w-]+\.)*\w[\w-]{0,66})\.([az]{2,6}(?:\.[az]{2})?)$)|(@\[?((25[0-5]\.|2[0-4][0-9]\.|1[0-9]{2}\.|[0-9]{1,2}\.))((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.){2}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\]?$)/i'; $phoneno_pattern = '^/\(?(\d{3})\)?[- ]?(\d{3})[- ]?(\d{4})$/'; if(preg_match($email_pattern,$input_email)) { // valid email. } if(preg_match($phoneno_pattern,$input_ph)) { // valid ph num. } 

You could use a regular expression directly as an argument to a function instead of using a variable.

+1
source

Source: https://habr.com/ru/post/1306678/


All Articles