2010-10-20 42 views
0

五(5)话,我想知道我可以使用PHP只允许五(5)上的文本输入字。限制文本输入,只允许在PHP

我知道,我可以用字符数的strlen功能,但我想知道我怎么可以的话去做。

+3

你或许应该测试字符串的长度和空格数量像布莱恩展示了。如果你不测试总长度oneCanWriteAVeryLongTextThatCountsOnlyAsOneWordAndThatsProbablyNotWhatYouWant。 – some 2010-10-20 02:34:49

回答

7

,您可以尝试这样的:

$string = "this has way more than 5 words so we want to deny it "; 

//edit: make sure only one space separates words if we want to get really robust: 
//(found this regex through a search and havent tested it) 
$string = preg_replace("/\\s+/", " ", $string); 

//trim off beginning and end spaces; 
$string = trim($string); 

//get an array of the words 
$wordArray = explode(" ", $string); 

//get the word count 
$wordCount = sizeof($wordArray); 

//see if its too big 
if($wordCount > 5) echo "Please make a shorter string"; 

应该工作:-)

+0

+1修剪开始和结束空格 – Ben 2010-10-20 02:38:52

+0

谢谢。第二个想法是,这不会处理单词之间有多个空格的情况..我想我会编辑它。 – 2010-10-20 02:52:05

+0

不错的安迪! @getawey我会去这个:) – Trufa 2010-10-20 02:52:53

0

你必须做两次,使用在客户端的JavaScript一次,然后使用PHP的服务器端。

0

你可以指望的空格数...

$wordCount = substr_count($input, ' '); 
+0

这不是['count_chars'](http://php.net/manual/en/function。count-chars.php),这个例子完全被破坏了。你甚至不会将字符串传递给函数。 – meagar 2010-10-20 02:42:42

+0

根据微薄的评论编辑更正。 – 2010-10-20 02:56:28

1

如果$输入你的输入字符串,

$wordArray = explode(' ', $input); 
if (count($wordArray) > 5) 
    //do something; too many words 

虽然我真的不知道为什么你会想这样做用php输入验证。如果您只是使用javascript,则可以在表单提交之前让用户有机会更正输入内容。

+3

使用PHP做输入验证是绝对必要的。 JavaScript可以并将在程序生命周期的正常过程中绕过。 – meagar 2010-10-20 02:33:12

+0

它应该一起完成。 – 2010-10-20 02:58:44

2

如果你这样做;

substr_count($_POST['your text box'], ' '); 

它限制到4

0

在PHP中,使用分割功能通过space.So你把它分解会得到词语的数组。然后检查数组的长度。

$mytextboxcontent=$_GET["txtContent"]; 

$words = explode(" ", $mytextboxcontent); 
$numberOfWords=count($words); 

if($numberOfWords>5) 
{ 
    echo "Only 5 words allowed"; 
} 
else 
{ 
    //do whatever you want.... 
} 

我没有测试this.Hope这个工程。我现在没有在我的机器上设置PHP环境。

1
从所有这些漂亮的解决方案,使用爆炸

除了()或substr_count(),为什么不直接使用PHP的内置函数计算字符串中的单词的数量。我知道这个功能名称并不特别直观,但:

$wordCount = str_word_count($string); 

将是我的建议。

注意,在使用多字节字符集时,这是不一定很有效。在这种情况下,是这样的:

define("WORD_COUNT_MASK", "/\p{L}[\p{L}\p{Mn}\p{Pd}'\x{2019}]*/u"); 

function str_word_count_utf8($str) 
{ 
    return preg_match_all(WORD_COUNT_MASK, $str, $matches); 
} 

建议的str_word_count()手册页