I tried converting this:
$regex = "/^[0-9]+[0-9\.]*(?<!\.)$/"
to all of these, but none are correct:
var regex = /^(?!\.$)[0-9]+[0-9\.]*/;
var regex = /^(?!.*\.$)[0-9]+[0-9\.]*/;
var regex = /^[0-9]+[0-9\.]*(?!\.$)/;
The PHP regex correctly rejects 1.1a and 1., but the javascript regex's do not.
Your PHP Regex may be better written as the following, which matches the same language, but is easier to read and doesn't need to use a negative look-behind:
$regex = "/^\d+(\.\d+)*$/"
It is also easy to translate it directly to a Javascript regex:
var regex = /^\d+(\.\d+)*$/;
Related
I'm trying to write a very simple markup language in PHP that contains tags like [x=123], and I need to be able to match that tag and extract only the value of x.
I'm assuming the answer involves regex but maybe I'm wrong.
So if we had a string:
$str = "F9F[x=]]^$^$[x=123]#3j3E]]#J";
And a regular expression to match:
/^\[x=.+\]$/
How would we get only the ".+" portion of the matching string into a variable?
You can use preg_match to search a string for a regular expression.
Check out the documentation here: http://www.php.net/manual/en/function.preg-match.php for more information on how to use it (as well as some examples). You might also want to take a look at preg_grep.
Following code should work for you:
$str = "F9F[x=]]^$^$[x=123]#3j3E]]#J";
if (preg_match('~\[x=(?<valX>\d+)\]~', $str, $match))
echo $match['valX'] . "\n";
OUTPUT:
123
I understand how to use PHP's preg_match() to extract a variable sequence from a string. However, i'm not sure what to do if there are 2 variables that I need to match.
Here's the code i'm interested in:
$string1 = "help-xyz123#mysite.com";
$pattern1 = '/help-(.*)#mysite.com/';
preg_match($pattern1, $string1, $matches);
print_r($matches[1]); // prints "xyz123"
$string2 = "business-321zyx#mysite.com";
So basically I'm wondering how to extract two patterns: 1) Whether the string's first part is "help" or "business" and 2) whether the second part is "xyz123" vs. "zyx321".
The optional bonus question is what would the answer look like written in JS? I've never really figured out if regex (i.e., the code including the slashes, /..../) are always the same or not in PHP vs. JS (or any language for that matter).
The solution is pretty simple actually. For each pattern you want to match, place that pattern between parentheses (...). So to extract any pattern use what've you already used (.*). To simply distinguish "help" vs. "business", you can use | in your regex pattern:
/(help|business)-(.*)#mysite.com/
The above regex should match both formats. (help|business) basically says, either match help or business.
So the final answer is this:
$string1 = "help-xyz123#mysite.com";
$pattern1 = '/(help|business)-(.*)#mysite.com/';
preg_match($pattern1, $string1, $matches);
print_r($matches[1]); // prints "help"
echo '<br>';
print_r($matches[2]); // prints "xyz123"
The same regex pattern should be usable in Javascript. You don't need to tweak it.
Yes, Kemal is right. You can use the same pattern in javascript.
var str="business-321zyx#mysite.com";
var patt1=/(help|business)-(.*)#mysite.com/;
document.write(str.match(patt1));
Just pay attention at the return value from the functions that are different.
PHP return an array with more information than this code in Javascript.
I have those two lines of code written in python i want to convert them to php, please help i don't know how to do this in php.
#code in python:
vowels= re.compile(ur'[\u064B-\u0652]')
newstr = vowels.sub('', str)
thank you
I think this is equivalent:
<?php
$vowels ='/[\x{064B}-\x{0652}]/u';
$newstr = preg_replace($vowels,"",$str);
The string should be UTF-8 encoded.
I believe what you want is PHP's preg_replace(). I have no idea how PHP handles Unicode so I'm unsure if you can just take the Python pattern as-is and use it with PHP, but the syntax for using preg_replace() would be something like this:
<?php
$mystring = "jask;lfjalksdf"
$pattern = "/\u064B-\u0652/";
$replacement = "";
echo preg_replace($pattern, $replacement, $mystring);
?>
re.compile() means its compiling a regular expression. Look at this for some help.
The sub function is essentially adding str to the beginning of the regular expression.
More info on python regular expressions can be found here
I am using a regular expression in javascript and want to do server side validation as well with the same regular expression. Do i need to modify it to make it compatible or will it run as it is.
How to use PHP regular expresion. Please provide a small example.
Thanks in Advance
EDIT
For Email Validation
var pattern = new RegExp(/^(("[\w-\s]+")|([\w-]+(?:\.[\w-]+)*)|("[\w-\s]+")([\w-]+(?:\.[\w-]+)*))(#((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{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);
For Phone no validation
var pattern = new RegExp(/^\(?(\d{3})\)?[- ]?(\d{3})[- ]?(\d{4})$/);
PHP regexp are based on PCRE (Perl Compatible Regular Expression).
Example (find digits) :
preg_match('/^[0-9]*$/', 'my01string');
See php documentation.
Javascript regexp are 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.
Supposed to work for most of the patterns, except escaping special characters and backslashes, but not reverse, php regex have features than javascript like look behind expressions.
javascript : /[a-z]+/
php : '/[a-z]+/'
For example,
var pattern = new RegExp(/^\(?(\d{3})\)?[- ]?(\d{3})[- ]?(\d{4})$/);
would be '/^\(?(\d{3})\)?[- ]?(\d{3})[- ]?(\d{4})$/' in php
You should use one of the following functions preg_match or preg_match_all. And with a bit of luck you shouldn't need to modify your regex.
PHP regex uses the classic Perl regex, so a match would look like
preg_match_all('/([a-zA-Z0-9]+)/', $myStringToBeTested, $results);
Later edit:
$string="test#mail.com";
if(preg_match('/^(("[\w-\s]+")|([\w-]+(?:\.[\w-]+)*)|("[\w-\s]+")([\w-]+(?:\.[\w-]+)*))(#((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{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!
In PHP we use the function preg_match.
$email_pattern = '/^(("[\w-\s]+")|([\w-]+(?:\.[\w-]+)*)|("[\w-\s]+")([\w-]+(?:\.[\w-]+)*))(#((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{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 have used the regex directly as the function argument instead of using a variable.
I have the following regex in PHP:
/(?<=\')[^\'\s][^\']*+(?=\')|(?<=")[^"\s][^"]*+(?=")|[^\'",\s]+/
and I would like to port it to javascript like:
var regex = new RegExp('/(?<=\')[^\'\s][^\']*+(?=\')|(?<=")[^"\s][^"]*+(?=")|[^\'",\s]+/');
var match = regex.exec("hello,my,name,is,'mr jim'")
for( var z in match) alert(match[z]);
There is something that JavaScript doesnt like here, but I have no idea what it is. I've tried looking for diferences between PHP and JS regex via regular-expressions.info but I cant see anything obvious.
Any help would be greatly appreciated
Thank you again
Edit:
The problem seems to lie within the positive lookbehind's but does this mean it cannot be ported?
Correct - the positive lookbehinds will not work.
But, just as some general information about regex in Javascript, here's a couple pointers for you.
You don't have to use the RegExp object - you can use pattern literals instead
var regex = /^[a-z\d]+$/i;
But if you use the RegExp object, you have to escape your backslashes since your pattern is now locked in a string.
var regex = new RegExp( '^[a-z\\d]+$', 'i' );
The primary benefit of the RegExp object is if there is a dynamic bit to your pattern, for example
var max = 4;
var regex = new RegExp( '\d{1,' + max + '}' );
You don't get lookbehind (and lookahead has problems in IE, so is best avoided too). But it's easy to just let those ' and " characters be part of the match, and throw them out afterwards:
var value= "hello,my,name,is,'mr jim'";
var match;
var r= /'[^'\s][^']*'|"[^"\s][^"]*"|[^'",\s]+/g;
while(match= r.exec(value)) {
var text= match[0];
if ('"\''.indexOf(text.charAt(0))!=-1) // starts with ' or "?
text= text.substring(1, text.length-1);
alert(text);
}
Or, use capturing parentheses to isolate the quotes from the text:
var r= /'([^'\s][^']*)'|"([^"\s][^"]*)"|([^'",\s]+)/g;
while (match= r.exec(value)) {
var text= match[1] || match[2] || match[3];
alert(text);
}
(I'm guessing your for(var z in match) was supposed to loop over each pattern match in the string. Unfortunately JavaScript doesn't quite work that easily.)
This may not be the best way to parse a comma-separated list; it seems a bit ill-defined for cases where you have a space or quote in the middle of a field. A simple string-indexing parser might be a better bet.
it's (?<=) positive look-behind what Javascript doesn't support. but be aware that Javascript implementation in different browsers vary significantly.
Edit: there is an SO question devoted to workaround.