我有一个从PHP脚本中获取输入的文本区域,我想在文本区域中计算单词或换行的数量,并在文本区域下面回显它。
这是textarea的代码看起来的样子。
<textarea name="domains" cols="120" rows="5" style="max-width:100%;">
<?php $output_array = explode(" ",$output);
$count = count($output_array);
for ($i=0;$i<$count;$i++){
echo $output_array[$i]."\n";
}
?>
</textarea><br />
<br>
<?php
preg_match_all("/(\n)/", $_POST['domains'], $matches);
$total_lines = count($matches[0]) + 1;
echo $total_lines;
?>
<br />
我尝试使用preg_match_all,但无论文本区域内有多少换行符,得到的输出只有“1”。
$str = 'as aa frd sad as
kjhsdf sdkjh
sd sdkjhsdf
sjkldhfh sdfjh sd';
preg_match_all("/\w+/", $str, $matches);
echo 'Words = ' . count($matches[0]);
echo PHP_EOL;
preg_match_all("/\n/", $str, $matches);
echo 'newlines = ' . count($matches[0]);
echo PHP_EOL;
echo 'So number of line is = ' . count($matches[0])+1;
结果
Words = 12
newlines = 3
So number of line is = 4