I'm looking for a way to write the following in only one preg_replace
$url = "stackoverflow";
if(!preg_match('/apple/',$url)){
$url = $url.".apple.com";
}
$str = 'something';
echo preg_replace('/^(?:(?!apple).)*$/is', '$0.apple.com', $str);
ps: modifiers is
might be useful.
(?: )*
makes non-capturing pattern. It matches zero or more instances of a (?!apple)
. Which is anything except of apple
and $0
tells to take the whole string when pattern is matched. Example suggested above is not the same, because it will match anything when the string does not start with apple
as ?!apple
condition is applied only once, at the beginning of the string.
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.