尽我所能,我似乎无法找到正确的正则表达式来找到我在这里所追求的内容。
我只想从以下内容中选择与域 www.myweb.com 匹配的第一个 URL 实例...
Some text https://www.myweb.com/page/cat/323123442321-rghe432 and then another https://www.adifferentsite.com/fsdhjss/erwr
我需要完全忽略第二个网址 www.a differentsite.com 并仅使用与 www.myweb.com 匹配的第一个网址,忽略任何其他可能的实例www.myweb.com
一旦发现第一个匹配的域,我需要存储其后的其余网址...
page/cat/323123442321-rghe432
...进入一个新变量 $newvar,所以...
$newvar = 'page/cat/323123442321-rghe432';
我正在努力:
return preg_replace_callback( '/http://www.myweb.com/\/[0-9a-zA-Z]+/', array( __CLASS__, 'my_callback' ), $newvar );
我已经阅读了大量有关如何检测 url 的文档,但找不到有关检测特定 url 的任何内容。
我真的不知道如何制定正则表达式,所以这个公式是不正确的。任何帮助将不胜感激。
编辑将问题编辑得更具体一些,希望更容易解决。
最佳答案
您可以使用 preg_replace_callback
并将一个数组传递给匿名函数(或只是您的自定义回调函数),以用所有必要的 URL 部分填充它。
这里是 demo :
$rests = array();
$re = '~\b(https?://)www\.myweb\.com/(\S+)~';
$str = "Some text https://www.myweb.com/page/cat/323123442321-rghe432 and then another https://www.adifferentsite.com/fsdhjss/erwr";
echo $result = preg_replace_callback($re, function ($m) use (&$rests) {
array_push($rests, $m[2]);
return $m[1] . "embed.myweb.com/" . $m[2];
}, $str) . PHP_EOL;
print_r($rests);
结果:
Some text https://embed.myweb.com/page/cat/323123442321-rghe432 and then another https://www.adifferentsite.com/fsdhjss/erwr
Array
(
[0] => page/cat/323123442321-rghe432
)
简单说几句:
'~\b(https?://)www\.myweb\.com/(\S+)~'
的~
为 regex delimiter ,所以你不必转义/
- 它是用单引号文字声明的,因此您不必对
\\S
使用双转义 - 它匹配并捕获 capturing groups 2个子字符串:
\b(https?://)
(匹配整个单词http
或https
后跟://
)和(\S+)
(匹配 1 个或多个非空白字符)。这些捕获组在模式中用(...)
标记,可以通过$matches[n]
访问,其中 n 是 id捕获组的。
更新
如果您只需要替换第一次出现的 URL,请将 limit 参数传递给 preg_replace_callback
:
$rest = "";
$re = '~\b(https?://)www\.myweb\.com/(\S+\b)~';
$str = "Some text https://www.myweb.com/page/cat/323123442321-rghe432, another http://www.myweb.com/page/cat/323123442321-rghe432 and then another https://www.adifferentsite.com/fsdhjss/erwr";
echo $result = preg_replace_callback($re, function ($m) use (&$rest) {
$rest = $m[2];
return $m[1] . "embed.myweb.com/" . $m[2];
}, $str, 1) . PHP_EOL;
//-LIMIT ^ - HERE -
echo $rest;
关于php - 正则表达式仅适用于 URL 中的特定域名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34042587/