简体   繁体   English

哪里在Regex中放置结尾定界符?

[英]Where to put the ending delimiter in a Regex ?

Im quite terrible at regex! 我在正则表达式中非常糟糕! can you guys show me where to put the ending delimiter in this piece of code? 你们可以告诉我在这段代码中将结尾定界符放在哪里吗?

$data = preg_replace("/ href=\"\/i", " href=\"{$domain}/", $data);
$data = preg_replace("/ src=\"\/i", " href=\"{$domain}/", $data);

The syntax is as follows: 语法如下:

preg_replace("/PATTERN/FLAGS", "Replace String", $subject);

As you can see, the delimiters are around a pattern , so in your case, your delimiters are in place. 如您所见,定界符在pattern周围,​​因此在您的情况下,定界符就位。

However, you also placed a delimiter in the replace string argument, which you shouldn't have. 但是,您也将分隔符放在了不应该使用的替换字符串参数中。 You also need to escape characters like the backslash \\ . 您还需要转义反斜杠\\等字符。 So the correct form would be: 因此正确的形式是:

$data = preg_replace("/ href=\"\\/i", " href=\"{$domain}\\", $data);
$data = preg_replace("/ src=\"\\/i", " href=\"{$domain}\\", $data);

That code will replace any instance of href="\\ with href="DOMAIN\\ . 该代码将用href="DOMAIN\\替换href="\\任何实例。

However, for that particular piece of replacement, RegEx is not necessary. 但是,对于特定的替换零件,RegEx不是必需的。 You could use a simple str_replace() : 您可以使用简单的str_replace()

$data = str_replace('href="\\', "href=\"{$domain}\\", $data);
$data = str_replace('src="\\', "src=\"{$domain}\\", $data);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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