简体   繁体   English

是否可以在php中使用正则表达式替换URL?

[英]Is it possible to replace a URL using regular expression in php?

Input text: Our website is <a href="www.me.com">www.me.com</a> 输入文字: Our website is <a href="www.me.com">www.me.com</a>

Output required: Our website is <a href="[x]">[x]</a> 要求输出: Our website is <a href="[x]">[x]</a>

Rule: any url needs to be replaced by [x]. 规则:任何网址都需要替换为[x]。 URL might be with http/https or www or simply me.com. URL可能带有http / https或www或只是me.com。 The solution needs to be case insensitive 解决方案必须不区分大小写

$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);

Thanks for any suggestions. 感谢您的任何建议。

Never parse HTML with regular expressions. 切勿使用正则表达式解析HTML。 It might seems like overkill to use a DOM parser for a job like this, but you're guaranteed to avoid problems at some point in the future. 对这样的工作使用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();

What about this to grab, http/https and with www or without www urls? 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;

Output: <a href="[x]">[x]</a> 输出: <a href="[x]">[x]</a>

Regex https://regex101.com/r/X4vrOt/2 正则表达式 https://regex101.com/r/X4vrOt/2

DEMO: https://3v4l.org/fFhOk 演示: https : //3v4l.org/fFhOk

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

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