任意の http/url からタグを消去する PHP ソリューションを考え出す正規表現の忍者はいますか?ただし、テキストの残りの部分にはタグを残しますか?
例えば:
the word <cite>printing</cite> is in http://www.thisis<cite>printing</cite>.com
なる必要があります:
the word <cite>printing</cite> is in http://www.thisisprinting.com
これは私がすることです:
<?php
//a callback function wrapper for strip_tags
function strip($matches){
return strip_tags($matches[0]);
}
//the string
$str = "the word <cite>printing<cite> is in http://www.thisis<cite>printing</cite>.com";
//match a url and call the strip callback on it
$str = preg_replace_callback("/:\/\/[^\s]*/", 'strip', $str);
//prove that it works
var_dump(htmlentities($str));
この置換に適切な正規表現は次のようになります。
#(https?://)(.*?)<cite>(.*?)</cite>([^\s]*)#s
s
すべての改行で一致するフラグ。
タグ間の選択を使用しlazy
て、より類似したタグをエスケープしないように正確にします
スニペット:
<?php
$str = "the word <cite>printing<cite> is in http://www.thisis<cite>printing</cite>.com";
$replaced = preg_replace('#(https?://)(.*?)<cite>(.*?)</cite>([^\s]*)#s', "$1$2$3$4", $str);
echo $replaced;
// Output: the word <cite>printing<cite> is in http://www.thisisprinting.com