" € á ...
REGEXを使用して文字列からのようなすべてのHTMLコードを削除したい。
弦:"This is a string " € á &"
必要な出力:This is a string
あなたが試すことができます
$str="This is a string " € á &";
$new_str = preg_replace("/&#?[a-z0-9]+;/i",'',$str);
echo $new_str;
これがうまくいくことを願っています
説明:
& - starting with
# - some HTML entities use the # sign
?[a-z0-9] - followed by
;- ending with a semi-colon
i - case insensitive.
preg_replace('#&[^;]+;#', '', "This is a string " € á &");
これを試して:
preg_replace('/[^\w\d\s]*/', '', htmlspecialchars_decode($string));
ただし、削除したくないものを削除する場合があります。正規表現を変更する必要がある場合があります。
$str = preg_replace_callback('/&[^; ]+;/', function($matches){
return html_entity_decode($matches[0], ENT_QUOTES) == $matches[0] ? $matches[0] : '';
}, $str);
これは機能€
しますが、HTML 4 のエンティティではないため、削除されません。PHP 5.4 を使用している場合は、フラグENT_QUOTES | ENT_HTML5
を使用して、のような HTML5 エンティティで正しく動作させることができます€
。
エンティティを完全に削除しようとしている場合 (つまり、エンティティをデコードしない場合) は、次のことを試してください。
$string = 'This is a string " € á &';
$pattern = '/&([#0-9A-Za-z]+);/';
echo preg_replace($pattern, '', $string);