开发者

Convert Regexp in Js into PHP?

开发者 https://www.devze.com 2023-04-10 07:05 出处:网络
I have the following regular expression in javascript and i would like to have the exact same functionality (or similar) in php:

I have the following regular expression in javascript and i would like to have the exact same functionality (or similar) in php:

// -=> REGEXP - match "x bed" , "x or y bed":
var subject = query;
var myregexp1 = /(\d+) bed|(\d+) or (\d+) bed/img;
var match = myregexp1.exec(subject);
while (match != null){
    if (match[1]) {   "X => " + match[1]; }
    else{          开发者_JS百科   "X => " + match[2] + " AND Y => "  + match[3]}
    match = myregexp1.exec(subject);
}

This code searches a string for a pattern matching "x beds" or "x or y beds". When a match is located, variable x and variable y are required for further processing.

QUESTION:

How do you construct this code snippet in php?

Any assistance appreciated guys...


You can use the regex unchanged. The PCRE syntax supports everything that Javascript does. Except the /g flag which isn't used in PHP. Instead you have preg_match_all which returns an array of results:

preg_match_all('/(\d+) bed|(\d+) or (\d+) bed/im', $subject, $matches, 
    PREG_SET_ORDER);
foreach ($matches as $match) {

PREG_SET_ORDER is the other trick here, and will keep the $match array similar to how you'd get it in Javascript.


I've found RosettaCode to be useful when answering these kinds of questions.

It shows how to do the same thing in various languages. Regex is just one example; they also have file io, sorting, all kinds of basic stuff.


You can use preg_match_all( $pattern, $subject, &$matches, $flags, $offset ), to run a regular expression over a string and then store all the matches to an array.

After running the regexp, all the matches can be found in the array you passed as third argument. You can then iterate trough these matches using foreach.

Without setting $flags, your array will have a structure like this:

$array[0] => array ( // An array of all strings that matched (e.g. "5 beds" or "8 or 9 beds" )
    0 => "5 beds",
    1 => "8 or 9 beds"
);
$array[1] => array ( // An array containing all the values between brackets (e.g. "8", or "9" )
    0 => "5",
    1 => "8",
    2 => "9"
 );

This behaviour isn't exactly the same, and I personally don't like it that much. To change the behaviour to a more "JavaScript-like"-one, set $flags to PREG_SET_ORDER. Your array will now have the same structure as in JavaScript.

$array[0] => array(
    0 => "5 beds", // the full match
    1 => "5", // the first value between brackets
);
$array[1] => array(
    0 => "8 or 9 beds",
    1 => "8",
    2 => "9"
);
0

精彩评论

暂无评论...
验证码 换一张
取 消