its*_*sme 0 php string trim filter
我只需要从一个字符串中取出完整的单词,我的意思是完整的单词=有超过4个字符的单词.字符串示例:
"hey hello man are you going to write some code"
Run Code Online (Sandbox Code Playgroud)
我需要回到:
"hello going write some code"
Run Code Online (Sandbox Code Playgroud)
此外,我需要修剪所有这些单词,并将它们放入一个简单的数组.
可能吗?
根据您的完整要求,如果您也需要未修改的字符串数组,您可以使用explode它,这样的事情会将您的单词放入数组中:
$str = "hey hello man are you going to write some code";
$str_arr = explode(' ', $str);
Run Code Online (Sandbox Code Playgroud)
然后您可以使用array_filter删除您不想要的单词,如下所示:
function min4char($word) {
return strlen($word) >= 4;
}
$final_str_array = array_filter($str_arr, 'min4char');
Run Code Online (Sandbox Code Playgroud)
否则,如果您不需要未修改的数组,您可以使用正则表达式来获取所有超过特定长度的匹配使用preg_match_all,或者替换掉使用的匹配preg_replace。
最后一个选择是按照基本方式进行操作,explode根据第一个代码示例使用来获取数组,然后使用循环遍历所有内容unset以从数组中删除条目。但是,您还需要重新索引(取决于您随后对“固定”数组的使用),这可能效率低下,具体取决于您的数组有多大。
编辑:不知道为什么有人声称它不起作用,请参阅下面的输出var_dump($final_str_array):
array(5) { [1]=> string(5) "hello" [5]=> string(5) "going" [7]=> string(5) "write" [8]=> string(4) "some" [9]=> string(4) "code" }
Run Code Online (Sandbox Code Playgroud)
@OP,要将其转换回您的字符串,您只需调用implode(' ', $final_str_array)即可获取此输出:
hello going write some code
Run Code Online (Sandbox Code Playgroud)
您可以使用正则表达式来执行此操作.
preg_replace("/\b\S{1,3}\b/", "", $str);
Run Code Online (Sandbox Code Playgroud)
然后你可以将它们放入一个数组中preg_split().
preg_split("/\s+/", $str);
Run Code Online (Sandbox Code Playgroud)
使用str_word_count() http://php.net/manual/fr/function.str-word-count.php
str_word_count($str, 1)
Run Code Online (Sandbox Code Playgroud)
将返回一个单词列表,然后使用多个n字母计数strlen()
使用str_word_count()其他解决方案的最大优点是,preg_match或者explode它会解释标点符号并将其从最终的单词列表中丢弃.
| 归档时间: |
|
| 查看次数: |
10294 次 |
| 最近记录: |