开发者

Regular expression matching multiple patterns

开发者 https://www.devze.com 2022-12-09 06:38 出处:网络
$url = \"example-com--folder\"; $searchArray = array(\'/-/\',\'/--/\'); $replaceArray = array(\'.\',\'/\');
$url = "example-com--folder";
$searchArray = array('/-/','/--/');
$replaceArray = array('.','/');
$url = preg_replace($searchArray, $replaceArray, $url);

The output I want is example.com/folder but all I get now is example.com..folder

I know this is because I don't have th开发者_运维问答e proper regex pattern, but what would that pattern be?


Change the order of the '/--/' and '/-/' patterns so that '/--/' is checked first, otherwise '/-/' will trump '/--/'. Don't interpolate the arrays in the call to preg_replace.

$url = "example-com--folder";
$searchArray = array('/--/', '/-/');
$replaceArray = array('/', '.');
$url = preg_replace($searchArray, $replaceArray, $url);

Alternatives:

  • Use multiple calls to preg_replace in the order you wish to evaluate the REs. This isn't as objectionable as you might think because preg_replace loops over the arrays and handles each RE in turn.
  • Use an evaluated replacement

    $url = "www-example-com--folder";
    $replacements = array('-' => '.', '--' => '/');
    $url = preg_replace('/(--?)/e', '$replacements["$1"]', $url);
    
  • Use a lookahead and lookbehind

    $url = "www-example-com--folder";
    $searchArray = array('/(?<!-)-(?!-)/', '/--/');
    $replaceArray = array('.', '/');
    $url = preg_replace($searchArray, $replaceArray, $url);
    


This is PHP, right?

You need a quantifier to specify that you want exactly two hyphens in the second pattern. Try:

$searchArray = array('/-/','/-{2}/');

The curly braces say 'require exactly n of the preceding pattern'

Here's a good reference.


See if this works:

$url = "example-com--folder";
$searchArray = array('([^-])-([^-])','--');
$replaceArray = array('$1.$2','/');
$url = preg_replace("$searchArray", "$replaceArray", $url);

what this says is "match any - that doesn't have a dash before or after and replace that with a ." and "match double -- with /". obviously, you can extend this to limit the second match to 2 dashes only by adding ([^-]) at the from and back. as it is, "-----" will become "//", which you may not want.

0

精彩评论

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