2016-01-30 23 views
1

我需要幫助檢測字符串包含的標點符號在其之前或之後或行尾沒有空格。PHP正則表達式用於測試字符串中沒有至少有一個空格的標點符號

這是我很難言傳,所以我會用例嘗試:

這應該通過測試:

hello, my friend 
hello ,my friend 
hello , my friend 
hello my friend 
hello my friend. 

這將失敗測試:

hello,my friend 
hello, my friend,have a nice day 

的功能我希望是這樣簡單:

function punctest($str) 
{ 
    if (preg_match("[:punct:]",$str)) 
    { 
     if (SOME_REGEX_GOES_HERE) 
     { 
      $okay = 1; // punctuation found, but has a space before OR after it 
     } 
     else 
     { 
      $okay = 0; // punctuation found, not no space found either side 
     } 

    } 
    else 
    { 
     $okay = 1; // no punct found 
    } 
} 

回答

1

爲了詳細說明@里亞茲的回答,你只是想拒絕匹配/\S[[:punct:]]\S/字符串:

<?php                                  

function punctest($str) 
{ 
    return !preg_match('/\S[[:punct:]]\S/', $str); 
} 

var_dump(punctest('hello, my friend')); 
var_dump(punctest('hello,my friend')); 

打印

bool(true) 
bool(false) 
1

下面的正則表達式會在兩側找到帶有非空白字符的標點符號。 。修改使用任何標點符號你在特別感興趣

/\S[,;:.?!]\S/ 
相關問題