简体   繁体   中英

Concatenating variable into a regex php

I have these arrays (array and array2)

$urls = array("http://piggington.com/pb_cash_flow_positive")

I have this regular expression

(preg_match("/\/{2}.*?\./", $array[$i], $matches))

It checks for everything that comes after 2nd slash and before 1st dot. So it will find

/piggington.

Now want to concatenate a variable inside the following regular expression, so it will search for a specific string.

I tried:

$matches_imploded = implode($matches);
$matches_imploded = preg_quote($matches_imploded, '/');
$match_with_other_array = preg_grep("/\/{2}".$matches_imploded."\./", $array2);

But it's not finding any matches.. What am I doing wrong? It should be looking inside array2 and making a positive match with $matches_imploded

between second slash and first dot we found $matches_imploded

To match everything which comes after // and before the first dot, you need to use \\K or positive lookbehind.

preg_match("~/{2}\K[^.]*(?=.)~", $array[$i], $matches)
$matches_imploded = implode($matches);
$matches_imploded = preg_quote($matches_imploded, '/');
$match_with_other_array = preg_grep("/\/{2}".$matches_imploded."\./", $array2);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM