如何在php中的段落中找到具有相同长度的单词?

时间:2014-02-13 06:08:48

标签: php string

这是我的段落:

$string = "A country is a region legally identified as a distinct entity in political geography.

我试过了,

$word = str_word_count($string); but it returns number of words only.     

现在我想要计算长度为2的字母数。在给定的字符串中,它们是3个字母,数量为2。

在PHP中怎么可能?请帮我找出解决方案?

1 个答案:

答案 0 :(得分:1)

你可以这样做

<?php
$string = "A country is a region legally identified as a distinct entity in political geography.";
$arr = explode(' ',$string);
foreach($arr as $val)
{
    if(strlen($val)==2)
    {
        echo "$val has a length of 2.<br>";
    }
}

<强> OUTPUT :

is has a length of 2.
as has a length of 2.
in has a length of 2.