我有段落。我想找到给定段落中的破折号码数
1.I opened ______ door and found ______ old man wearing ______ hat standing on _____ doorstep.
可能吗?
答案 0 :(得分:0)
您应该使用substr_count
只需在变量中声明您的文字并计算它
<?php
$text = "1.I opened ______ door and found ______ old man wearing ______ hat standing on _____ doorstep.";
echo substr_count($text,"_______");
?>
注意:它将计算_____
的数量。 [记录_____
计数为5
以下是demo
答案 1 :(得分:0)
好的,所以OP想要计算一系列下划线所代表的单词数量。
下划线的数量也可能有所不同,我猜这是代表单词的长度。
因此更通用的解决方案是...... 设置所需模式的正则表达式
$search_string = '/[^_]?[_]+[^_]?/'; // Looking for one or more '_' sequences
更简单的版本是
$search_string = '/[_]{2,}/'; // Looking for at least 2 '_' sequences
在需要的地方执行空白字数。
$word_count = preg_match_all($search_string,$text);
echo $word_count; // Just show the count for testing
正则表达式非常通用,但应该适用于上述情况。
附加:创建一个实现此功能的函数要好得多。
function count_blank_words($text){
$search_string = '/[_]{2,}/'; // Looking for at least 2 '_' sequences
return preg_match_all($search_string,$text);
}
并使用
调用它echo count_blank_words($text);