如何解决删除PHP字符串中的所有首字母缩写词
| 我有一排里面有首字母缩写词的文本有点像这样...$draft=\"The war between the CIA and NSA started in K2 when the FBI hired M\";
我一辈子都想不通如何创建一个删除所有首字母缩写词的新字符串。
我需要这个输出...
$newdraft=\"The war between the and started in when the hired\";
我能找到的唯一php函数只能删除您这样静态声明的单词!
$newdraft= str_replace(\"CIA\",\" \",$draft);
任何人有任何想法,或已经创建的功能?
解决方法
好的,让我们尝试写点东西(尽管我不明白它的用处是什么)。
<?php
function remove_acronyms($str)
{
$str_arr = explode(\' \',$str);
if (empty($str_arr)) return false;
foreach ($str_arr as $index => $val)
{
if ($val==strtoupper($val)) unset($str_arr[$index]);
}
return implode(\' \',$str_arr);
}
$draft = \"The war between the CIA and NSA started in K2 when the FBI hired M\";
print remove_acronyms($draft);
http://codepad.org/cIZSwwhV
,首字母缩写词的定义:完全大写且长度至少为2个字符的任何单词。
<?php
$draft=\"The war between the CIA and NSA started in K2 when the FBI hired M\";
$words = explode(\' \',$draft);
foreach($words as $i => $word)
{
if (!strcmp($word,strtoupper($word)) && strlen($word) >= 2)
{
unset($words[$i]);
}
}
$clean = implode(\' \',$words);
echo $clean;
?>
,尝试定义首字母缩写词。您必须做出一些努力,但是要说明“对于任何样例,“小于5个字符且大写的任何单个单词”都应该是正确的,并且您可以编写正则表达式为了那个原因。
除此之外,您可以列出大量的已知首字母缩写词,然后替换它们。
,正则表达式删除多个一起出现的大写字母和/或数字:
$draft=\"The war between the CIA and NSA started in K2 when the FBI hired M\";
$newdraft = preg_replace(\'/[A-Z0-9][A-Z0-9]+/\',\'\',$draft);
echo $newdraft;
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。