开发者

preg_match(_all) with a rule for every space character

I am trying to create a way of making sure that every space has at least three cha开发者_StackOverflowracters (a-zA-Z and single quotes are allowed) on each side of it. It does exactly that, however only with the first space. Not the rest of them. I tried preg_match_all() to no avail, hence my question/post to you guys.

<?PHP
  function validateSpaces($str) {
    if ( strpos( $str, ' ' ) !== FALSE && !preg_match( '/(([a-z\']{3,})([ ]{1})([a-z\']{3,}))/i', $str ) )
      return FALSE;

    return TRUE;
  }

  echo validateSpaces( 'Hey There' ); // Valid (correct)
  echo validateSpaces( 'He There' ); // Invalid (correct)
  echo validateSpaces( 'Hey Ther e' ); // Valid (incorrect)
?>

As you can see, the first two examples are working like they should, but the second one validates although the second space only has one character on the right side of it. Which is not what I want.

Any help or attempt to help is greatly appreciated!

Thank you in advance, Chris.


Last modification, will macth only if we have ony one space (trim string before trying to match it):

^([a-z']{3,} ?)+$


You could explode the string on spaces and check the array's contents.

Not complete solution:

$temb=explode(' ', $str);
$valid=true;
foreach ($temb as $tt) {
  if (strlen($tt)<3 || !{a preg_match for the right characters in $tt}) {
    $valid=false;
    break;
  }
}


Use preg_match_all() rather than preg_match(), and compare the number of results with a substr_count($str,' ') to see that every space matches your regexp criteria


How about this - you could combine the patterns into one if performance is an issue; I find more than one level of conditional logic difficult to read:

function validate( $value )
{
  $ptn_a = '/(^| )[A-Za-z\']{0,2} /';
  $ptn_b = '/ [A-Za-z\']{0,2}($| )/';

  if ( preg_match( $ptn_a, $value ) )
    return false;

  if ( preg_match( $ptn_b, $value ) )
    return false;

  return true;
}

var_dump( validate('Hey There') );
var_dump( validate('He There') );
var_dump( validate('Hey Ther e') );


function validate($string = '')


{


  $regexp = '/([^\w]|^)([\w]{1,2})([^\w]|$)/';

  if (strlen(trim($string)) && !preg_match($regexp, $string)) {
      return 'TRUE';
  }

  return 'FALSE';


}


print validate('   ');
print "\n";
print validate('Hey There');
print "\n";
print validate('He There');
print "\n";
print validate('Hey  ');
print "\n";
print validate('Hey Ther e');
print "\n";
print validate('Hey Th ere');

This can also help.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜