替换   带有空白或空字符串 PHP

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11733412/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 01:57:43  来源:igfitidea点击:

Replace   with a blank or empty string PHP

phpstr-replace

提问by Sandhurst

Well, I have tried these and it seems that none of them are working, my example string is

好吧,我已经尝试过这些,但似乎它们都不起作用,我的示例字符串是

 $text_description="       Hello world! lorel ipsum";

 $text_description= str_replace(" "," ",$text_description);
 $text_description = preg_replace("/&#?[a-z0-9]+;/i"," ",$text_description);
 $text_description=html_entity_decode($text_description);

回答by Michael Robinson

$text_description="       Hello world! lorel ipsum";
$text_description = str_replace(' ', ' ', $text_description);
echo $text_description;

Output:

输出:

Hello world! lorel ipsum

你好,世界!洛雷尔 ipsum

回答by Adam Ranganathan

A little late to answer but hopefully might help someone else. The most important thing while extracting content from html is to use utf8_decode()in php. Then all other string operations become a breeze. Even foreign characters can be replaced by directly copy pasting characters from browser into the php code. The following function replaces  with empty character. Then all extra white spaces are replaced with a single white space using preg_replace(). Leading and trailing white spaces are removed in the end using trim().

回答有点晚,但希望可以帮助别人。从 html 中提取内容时最重要的是在 php 中使用utf8_decode()。然后所有其他字符串操作变得轻而易举。甚至可以通过直接从浏览器复制粘贴字符到php代码中来替换外来字符。以下函数替换 为空字符。然后,所有额外的空格都使用preg_replace(). 最后使用 删除前导和尾随空格trim()

function clean($str)
{       
    $str = utf8_decode($str);
    $str = str_replace(" ", "", $str);
    $str = preg_replace('/\s+/', ' ',$str);
    $str = trim($str);
    return $str;
}

$html = "       Hello world! lorel ipsum";
$output = clean($html);
echo $output;

Hello world! lorel ipsum

你好,世界!洛雷尔 ipsum

回答by Anas

You Can just html_entity_decode()wich allow you to replace all html entities to their applicable characters for example :

您可以只使用html_entity_decode()至允许您将所有 html 实体替换为其适用的字符,例如:

 $HtmlText="it's Working \"Correctly\"";
 $MyText=html_entity_decode($HtmlText);
 echo $MyText; // "it's Working "Correctly"

I Wish that is helpfull ! ;)

我希望这是有帮助的!;)