使用php生成纯文本
我正在使用一个以生成的字符串结束的服务。字符串通常类似于:使用php生成纯文本,php,string,Php,String,我正在使用一个以生成的字符串结束的服务。字符串通常类似于: Hello Mr John Doe, you are now registered \t. Hello &nbsb; Mr John Doe, your phone number is &nbsb; 555-555-555 &nbs; \n 我需要删除所有html实体以及所有\t和\n等 我可以使用html\u entity\u decode,来
Hello Mr John Doe, you are now registered \t.
Hello &nbsb; Mr John Doe, your phone number is &nbsb; 555-555-555 &nbs; \n
我需要删除所有html实体以及所有\t和\n等
我可以使用
html\u entity\u decode
,来删除不间断空格,使用str\u replace
来删除\t
或\n
,但是有更通用的方法吗?一些东西可以确保字符串中只存在字母字符(一些不包含代码的字符串)。如果我正确理解您的大小写,您基本上希望从HTML转换为纯文本
根据输入的复杂性以及所需的健壮性和准确性,您有两种选择:
- 用于删除HTML标记,使用
作为源编码对实体进行解码,或进行任何其他替换:HTML-ENTITIES
$html = "<p>Hello Mr John Doe, you are now registered. Hello Mr John Doe, your phone number is 555-555-555 Test: €/é</p>"; $plain_text = $html; $plain_text = strip_tags($plain_text); $plain_text = mb_convert_encoding($plain_text, 'UTF-8', 'HTML-ENTITIES'); $plain_text = strtr($plain_text, [ "\t" => ' ', "\r" => ' ', "\n" => ' ', ]); $plain_text = preg_replace('/\s+/u', ' ', $plain_text); var_dump($html, $plain_text);
string(169) "<p>Hello Mr John Doe, you are now registered.
Hello Mr John Doe, your phone number is 555-555-555
Test: €/é</p>"
string(107) "Hello Mr John Doe, you are now registered. Hello Mr John Doe, your phone number is 555-555-555 Test: €/é"
string(169)”你好,约翰·多伊先生,您现在已注册。
你好,John Doe先生,你的电话号码是555-555-555
测试:&euro;/é;“
字符串(107)“你好,John Doe先生,您现在已注册。你好,John Doe先生,您的电话号码是555-555-555测试:€/
字母表字符取决于您对字母表的定义。从技术上讲是五个字母字符。@Gordon我指的是一个不包含任何代码的字符串。是否尝试使用实际输入的heredoc语法?你的意思是你已经破坏了HTML实体和PHP转义序列的混合吗?你有一个很好的完整答案可以尝试。我不确定您是否要删除它们。如果你有史密斯先生,并且你移除了这个字符串,那么你会得到一个错误的字符串:当它应该是史密斯先生时,是史密斯先生。如果你有'他说'你好',那么你就没有'他说'你好'。对我来说,这是破坏原始输入。看看阿尔瓦罗的回答。如果您想删除其他无关的空间,您可以使用他提供的技术,使用正则表达式删除多余的空间。
string(169) "<p>Hello Mr John Doe, you are now registered.
Hello Mr John Doe, your phone number is 555-555-555
Test: €/é</p>"
string(107) "Hello Mr John Doe, you are now registered. Hello Mr John Doe, your phone number is 555-555-555 Test: €/é"