Reputation: 121
In our one project we are appending css background image url with certain path in php that does not starts with 'http', 'website' or 'vendor', so far our expression is doing good but it is also including starting quote in result. Any help is appriciated
here is my php code
$array=[
'url("images")',
'url (\'images\')',
'url(vendor/)',
'url(website/)',
"url(http://)"
];
$pattern = '/url\s*\(\s*[\'"]?\/?([^(http|vendor|website)].+?)[\'"]?\s*\)/i';
$result=[];
foreach ($array as $test_string) {
$content = preg_replace($pattern, 'url('.'websites/abc/www/'.'$1)', $test_string);
$result[$test_string] = $content;
}
var_dump($result);
and the result is as follows, note that quote at www/"images
array (size=5)
'url("images")' => string 'url(websites/abc/www/"images)' (length=29)
'url ('images')' => string 'url(websites/abc/www/'images)' (length=29)
'url(vendor/)' => string 'url(vendor/)' (length=12)
'url(website/)' => string 'url(website/)' (length=13)
'url(http://)' => string 'url(http://)' (length=12)
Any help is appreciated, thank you in advanced.
Upvotes: 1
Views: 386
Reputation: 48751
You are confusing brackets with parentheses in Regular Expressions. Former defines a character class and latter a group. To negate a pattern in match you should use negative lookarounds that here a negative lookahead provides a solution. You'd better make quotation marks and leading slash possessive by adding a +
sign after ?
:
url\s*\(\s*[\'"]?+\/?+((?!http|vendor|website).+?)[\'"]?\s*\)
url\s*\(\s*
Match a url(
with possible spaces around parenthesis[\'"]?+
Optional match of a quotation mark but if is matched no backtracking is allowed\/?+
Optional match of a slash mark but if is matched no backtracking is allowed((?!http|vendor|website).+?)
Capturing anything that doesn't start with patterns in negative lookahead[\'"]?\s*\)
Up to end of url
Upvotes: 1