我有一个包含很多单词的数组,但有些句子是大写的。例如:
THIS SENTENCE IS UPPERCASE
this sentece is in lowercase
我想用\r\n
将这两句话分开,但我找不到怎么做
以下是我如何检索此数组:
$result_pk_info = array();
while ($row = odbc_fetch_array($sql_pk_info))
{
$opisanie = iconv("cp1257", "UTF-8", trim($row['opis']));
$id = iconv("cp1257", "UTF-8", trim($row['pacientid']));
$date = iconv("cp1257", "UTF-8", trim($row['data']));
$desc = explode('@#$', $opisanie);
$all_info = "<tr><td>".$desc[1]."</td></tr>";
$result_pk_info[] = $all_info;
}
在$desc
中的我有单词数组,我想在其中搜索并分割大写和小写。
那么有人可以帮我吗?
UPD 我喜欢这种结构的文字:
SENTENCE IN UPPERCASE Sentece in lower case
答案 0 :(得分:1)
此功能正是您所需要的:
function split_upper_lower ($string)
{
$words = explode (' ', $string);
$i = 0;
foreach ($words as $word)
{
if (ctype_upper ($word))
$new_string_array[++$i]['type'] = 'UPPER';
else
$new_string_array[++$i]['type'] = 'LOWER';
$new_string_array[$i]['word'] = $word;
}
$new_string = '';
foreach ($new_string_array as $key => $new_word)
{
if (!isset ($current_mode))
{
if (ctype_upper ($new_word))
$current_mode = 'UPPER';
else
$current_mode = 'LOWER';
}
if ($new_word['type'] === $current_mode)
{
$new_string .= $new_word['word'];
if (isset ($new_string_array[$key + 1]))
$new_string .= ' ';
}
else
{
$new_string .= "\r\n" . $new_word['word'];
if (isset ($new_string_array[$key + 1]))
$new_string .= ' ';
if ($current_mode === 'UPPER') $current_mode = 'LOWER';
else $current_mode = 'UPPER';
}
}
return $new_string;
}
使用br
进行测试:
$string = 'HI how ARE you doing ?';
echo split_upper_lower ($string);
输出:
HI
how
ARE
you doing ?
答案 1 :(得分:0)
使用preg_match:http://php.net/manual/en/function.preg-match.php
$string = 'THIS SENTENCE IS UPPERCASE';
$string2 = 'this sentece is in lowercase';
if(preg_match ( '/[A-Z ]$/' , $string))
{
echo 'uppercase';
}
else
{
echo 'lowercase';
}
通过$ desc循环使用它。其中$ string是包含一个字符串的数组的一个元素。
/ [A-Z] $ /将使用空格匹配全部大写。您可以升级正则表达式以从字符串中获取其他内容。
答案 2 :(得分:0)
如果我理解你的问题,你可以这样做......
$desc = array ("abcd","ABCD","bbb","B");
foreach($desc as $value) {
if(ctype_upper($value)) {
// character is upper
} else {
// character is lower
}
}
答案 3 :(得分:0)
可以使用preg_match_all()
完成此操作。使用以下代码
$result_pk_info = array();
while ($row = odbc_fetch_array($sql_pk_info))
{
$opisanie = iconv("cp1257", "UTF-8", trim($row['opis']));
$id = iconv("cp1257", "UTF-8", trim($row['pacientid']));
$date = iconv("cp1257", "UTF-8", trim($row['data']));
$desc = explode('@#$', $opisanie);
//converting $desc array to string
$string = implode(" " , $desc);
//Upper case Matching
$upprCase = preg_match_all('/[A-Z]/', $string, $uprmatches, PREG_OFFSET_CAPTURE);
if($upprCase){
foreach ($uprmatches as $match)
{
foreach($match as $value)
//Iam a uppercase
print $UpperCase = $value[0];
}}
//Splitting with \r\n
print "\r\n";
//lower case matching
$lowrCase = preg_match_all('/[a-z]/', $string, $lowrmatches, PREG_OFFSET_CAPTURE);
if($lowrCase){
foreach ($lowrmatches as $match)
{
foreach($match as $value)
//Iam a lowercase
print $lowerCase = $value[0];
}}
}