Link to home
Start Free TrialLog in
Avatar of AndyPSV
AndyPSVFlag for United Kingdom of Great Britain and Northern Ireland

asked on

ctype_alpha - how to add space

j.e ( if ctype_alpha => true if there are white spaces inside)
function _surname($v) {
	if(!empty($v)) {
		if(!ctype_alpha($v)) $e .= '» Please use only alphabet(no digits) characters in surname (+ no spaces)'."\r";
		if(!lenght($v,2)) $e .= '» Surname must be above 2 letters lenght.'."\r";
	} return $e;
}

Open in new window

Avatar of Richard Quadling
Richard Quadling
Flag of United Kingdom of Great Britain and Northern Ireland image

I don't think you can alter ctype.

But a regex will do ...

if (0 == preg_match('`^^[a-z](?!.*  .*)[a-z ]+[a-z]$`i', $v)) $e .= '» Please use only alphabet(no digits) characters in surname (+ spaces)'."\r";

The regex is saying must start and end with a letter and may contain spaces and letters but not 2 spaces next to each other.


Avatar of AndyPSV

ASKER

The regex is saying must start and end with a letter and may contain spaces and letters but not 2 spaces next to each other.

How to modify this to trim the empty 2 spaces to one?
ASKER CERTIFIED SOLUTION
Avatar of Richard Quadling
Richard Quadling
Flag of United Kingdom of Great Britain and Northern Ireland image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Slight update. The regex can be simplified. See comments in the code below.
<?php
$a_Tests = array
        (
        ' ',
        '  ',
        '       starts with spaces',
        'ends with spaces         ',
        '      wrapped with spaces          ',
        'one space',
        'nospace',
        'lots    of    spaces'
        );
 
foreach($a_Tests as $s_Test)
        {
        echo str_pad("'$s_Test' ", 40) . ": ";
	// As we are trimming the string, no leading or trailing spaces.
	// As we replace 2+ spaces with 1 only single spaces.
	// So, the regex can be a lot simpler. Must match at least 1 letter or space
	// (though 1 space will never actually get to the regex test).
	// If you want to say there has to be at least 10 letters, use a regex of ...
	// '`^[a-z ]{10,}$`i'
	// The {10,} means at least 10 lettes.
	// If you want between 10 and 40 letters ...
	// '`^[a-z ]{10,40}$`i'
        if (0 == preg_match('`^[a-z ]+$`i', preg_replace('` +`', ' ', trim($s_Test, ' ')), $a_Matches))
                {
                echo "Failed to pass test.", PHP_EOL;
                }
        else
                {
                $s_Test = $a_Matches[0];
                echo "Passed test and was returned as '$s_Test'.", PHP_EOL;
                }
        }

Open in new window