2010-10-20 41 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()手冊頁