phpを使用してhtmlタグをスペース文字に置き換える方法を知っていますか?
表示したら
strip_tags('<h1>Foo</h1>bar');
結果として「foobar」が表示されますが、単語を分離するために必要なのは「foobar」です。
phpを使用してhtmlタグをスペース文字に置き換える方法を知っていますか?
表示したら
strip_tags('<h1>Foo</h1>bar');
結果として「foobar」が表示されますが、単語を分離するために必要なのは「foobar」です。
$string = '<h1>Foo</h1>bar';
$spaceString = str_replace( '<', ' <',$string );
$doubleSpace = strip_tags( $spaceString );
$singleSpace = str_replace( ' ', ' ', $doubleSpace );
これを試して。
preg_replace('#<[^>]+>#', ' ', '<h1>Foo</h1>bar');
Preg replaceはほとんどの場合問題ありませんが、ここで説明するように、1つのコーナーケースがあります。これは両方で機能するはずです。
strip_tags(str_replace('<', ' <', $str));
タグの前にスペースを追加すると、HTMLで有効になります。また、テキストに何らかの理由で「<」が含まれていて、その前にスペースを追加したくない場合など、いくつかの注意点があります。
user40521の例で自分自身を助けましたが、phpのstrip_tagsのような同じAPIで関数を作成しました。これは複数の変数を使用せず、トリムも行うため、開始/終了から単一の空白が削除されます。
/**
* @param string $string
* @param string|null $allowable_tags
* @return string
*/
function strip_tags_with_whitespace($string, $allowable_tags = null)
{
$string = str_replace('<', ' <', $string);
$string = strip_tags($string, $allowable_tags);
$string = str_replace(' ', ' ', $string);
$string = trim($string);
return $string;
}
これを試して:
$str = '<h1>Foo</h1>bar';
echo trim(preg_replace('/<[^>]*>/', ' ', $str));
preg_replace('#\<(.+?)\>#', ' ', $text);
答えが少し遅れますが、これを試してください。基本的に、タグを含む<>内のすべてを選択します。
>
このようなものは、どの属性にも含まれないことがわかっている場合に機能します。
preg_replace('/<[^>]+>/', ' ', 'hello<br>world');
正規表現ソリューションpreg_replace('/<[^>]*>/', ' ', $str)
では、次のようなイベント属性がある場合は機能しません。
<button onclick="document.getElementById('alert').innerHTML='<strong>MESSAGE</strong>';">
click</button>
もう1つ交換する必要があります。
<?php
$str =
"<div data-contents=\"<p>Hello!</p>\">Hi.</div>".
"Please<button onclick=\"document.getElementById('alert').innerHTML='".
"<strong>MESSAGE</strong>';\">click</button>here.";
$event =
"onafterprint|onbeforeprint|onbeforeunload|onerror|onhaschange|onload|onmessage|".
"onoffline|ononline|onpagehide|onpageshow|onpopstate|onresize|onstorage|onunload|".
"onblur|onchange|oncontextmenu|onfocus|oninput|oninvalid|onreset|onselect|onsubmit|".
"onkeydown|onkeypress|onkeyup|onclick|ondblclick|ondrag|ondragend|ondragenter|".
"ondragleave|ondragover|ondragstart|ondrop|onmousedown|onmouseenter|onmousemove|".
"onmouseleave|onmouseout|onmouseover|onmouseup|onscroll|onabort|oncanplay|".
"oncanplaythrough|oncuechange|ondurationchange|onemptied|onended|onerror|".
"onloadeddata|onloadedmetadata|onloadstart|onpause|onplay|onplaying|onprogress|".
"onratechange|onseeked|onseeking|onstalled|onsuspend|ontimeupdate|onvolumechange|".
"onwaiting|data-[^=]+";
$str = preg_replace("/<([^>]+)(".$event.")=(\"|')(?:(?!\\3).)+\\3/", "<$1", $str);
$str = preg_replace("/<[^>]*>/", " ", $str);
echo $str;
// with only strip_tags:
// Hi.Pleaseclickhere.
// with event and data attributes removal + regex tags removal:
// Hi. Please click here.
// with only regex tags removal:
// Hello! ">Hi. Please MESSAGE ';">click here.
?>
それが役に立てば幸い!
あなたが試すことができます
$str = '<h1>Foo</h1>bar';
var_dump(replaceTag($str,array("h1"=>"div")));
出力
string '<div>Foo</div>bar' (length=17)
使用した機能
function replaceTag($str,$tags) {
foreach ( $tags as $old => $new )
$str = preg_replace("~<(/)?$old>~", "<\\1$new>", $str);
return $str;
}
これらの埋め込み属性をstrip_tagsに依存している場合は、それが機能します。これを試して ...
function strip_tags_with_spacer(string $html, string $allowedTags) {
$allowedTagsArr=explode("<",strtolower(str_replace(">", "",$allowedTags)));
$tags=[];
$dom = new DOMDocument();
$dom->loadHTML($html);
$selector = new DOMXPath($dom);
$elements = $dom->getElementsByTagName('*');
foreach($elements as $child) $tags[$child->tagName]=$child->tagName;
foreach ( $tags as $tag ) {
if ( !in_array(strtolower($tag), $allowedTagsArr)) {
if ( in_array(strtolower($tag), ["p", "div", "h1", "h2", "h3", "h4", "pre", "body", "html", "form", "ul", "ol", "li", "table", "th", "td", "blockquote"])) $gap=" ";
else $gap="";
//echo "\nreplacing [$tag] with [$gap][$tag]";
$html = str_ireplace("</$tag", "$gap</$tag", $html);
}
}
return strip_tags($html, $allowedTags);
}
$result=strip_tags_with_spacer($str,"<button><b><u><i>");
詳細については、 http://sandbox.onlinephpfunctions.com/code/37299b1476dccb0631d404a073cf1c88f1cb7d2bを参照してください。
最初にstr_replaceを実行します
$string = '<h1>Foo</h1>bar'
strip_tags(str_replace('</h1>', ' ',$string));