是否可以在 php 中使用正则表达式替换 URL?
Is it possible to replace a URL using regular expression in php?
输入文字:Our website is <a href="www.me.com">www.me.com</a>
需要输出:Our website is <a href="[x]">[x]</a>
规则:任何 url 都需要用 [x] 替换。 URL 可能与 http/https 或 www 或只是 me.com。解决方案需要不区分大小写
$inputext = "<a href="www.me.com">www.me.com</a>";
$rule ="/(?<!a href=\")(?<!src=\")((http|ftp)+(s)?:\/\/[^<>\s]+)/i";
$replacetext = "[X]";
$outputext = preg_replace($rule, $replacetext, $inputext);
echo($outputext);
感谢任何建议。
http/https
有 www
或没有 www
url 的抓取怎么样?
<?php
$re = '/(https?:\/\/|(www\.)?[a-z0-9]+([\-\.]{1}[a-z0-9]+)*\.[a-z]{2,5}(:[0-9]{1,5})?(\/.*)?)/mi';
$str = 'Our website is <a href="www.me.com">www.me.com</a>';
$subst = '[x]';
$result = preg_replace($re, $subst, $str);
echo $result;
输出: <a href="[x]">[x]</a>
切勿使用正则表达式解析 HTML。使用 DOM 解析器来完成这样的工作似乎有些过分,但您可以保证在将来的某个时候避免出现问题。
$input = 'Our website is <a href="www.me.com">www.me.com</a>';
$replace = "[x]";
$dom = new DomDocument();
$dom->loadHTML($input, LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD);
$a = $dom->getElementsByTagName("a")->item(0);
$a->setAttribute("href", $replace);
$a->textContent = $replace;
echo $dom->saveHTML();
输入文字:Our website is <a href="www.me.com">www.me.com</a>
需要输出:Our website is <a href="[x]">[x]</a>
规则:任何 url 都需要用 [x] 替换。 URL 可能与 http/https 或 www 或只是 me.com。解决方案需要不区分大小写
$inputext = "<a href="www.me.com">www.me.com</a>";
$rule ="/(?<!a href=\")(?<!src=\")((http|ftp)+(s)?:\/\/[^<>\s]+)/i";
$replacetext = "[X]";
$outputext = preg_replace($rule, $replacetext, $inputext);
echo($outputext);
感谢任何建议。
http/https
有 www
或没有 www
url 的抓取怎么样?
<?php
$re = '/(https?:\/\/|(www\.)?[a-z0-9]+([\-\.]{1}[a-z0-9]+)*\.[a-z]{2,5}(:[0-9]{1,5})?(\/.*)?)/mi';
$str = 'Our website is <a href="www.me.com">www.me.com</a>';
$subst = '[x]';
$result = preg_replace($re, $subst, $str);
echo $result;
输出: <a href="[x]">[x]</a>
切勿使用正则表达式解析 HTML。使用 DOM 解析器来完成这样的工作似乎有些过分,但您可以保证在将来的某个时候避免出现问题。
$input = 'Our website is <a href="www.me.com">www.me.com</a>';
$replace = "[x]";
$dom = new DomDocument();
$dom->loadHTML($input, LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD);
$a = $dom->getElementsByTagName("a")->item(0);
$a->setAttribute("href", $replace);
$a->textContent = $replace;
echo $dom->saveHTML();