Hoping someone can help give a simple solution to splitting a first and last name when the full name has french or other accents on the characters.
This seems to work fine when when the name doesn't have any accents, but isn't working to detect the white space when there is an accent in the string.
An example name would be "Marc-André Côté"
$name = trim($FullNameInput);
$last_name = (strpos($name, ' ') === false) ? '' : preg_replace('#.*\s([\w-]*)$#', '$1', $name);
$first_name = trim( preg_replace('#'.$last_name.'#', '', $name ) );
Use a UNICODE modifier when dealing with Unicode strings and add a single quote since some names contain it:
preg_replace('#.*\s([\w\'-]*)$#u', '$1', $name)
The UNICODE modifier will also make \w Unicode aware. A preg_match solution will be cleaner though:
preg_match('/\s\K[\w\'-]+$/u', $name, $m)
You just need to check if there is a match. If there is a match, get $m[0], else assign an empty string to it.
You can use the explode Function. It runs with your example name without any problems and it´s much easier than your regex solution
$nameparts = explode(" ", $name);
echo $nameparts[0]; // First Name
echo $nameparts[1]; // Last Name
Related
I know there's are other ways to do it, but I'm playing with validating a name field using ctype_alpha but allowing spaces, hyphens, and apostrophes.
Per another post on Stack, I was able to add the spaces no problem, but I'm thinking I have the syntax wrong for replacing multiple characters.
What I've used so far that works for validating that only letters and spaces are allowed:
if (ctype_alpha(str_replace(' ', '', $name)) === false) {
echo'Name must contain letters and spaces only';
exit;
}
This removes any spaces before checking that the string is letters only. I was looking to simply add to this to also allow hyphens and apostrophes.
What I've tried for adding hyphens and/or apostrophes (doesn't work):
if (ctype_alpha(str_replace(' ', '', '-', '', $name)) === false) {
echo'Name must contain letters and spaces only';
exit;
}
My guess is that adding a second string in the str_replace function is not proper syntax, but being a PHP newb, I'm having a hard time figuring out how to phrase my searches to find the correct syntax.
Also, am I correct in saying that '\w' will cover my apostrophes once I figure out the correct syntax for the str_replace function?
Genuinely appreciate the help guys. You're all invaluable and I try hard not to abuse it.
the proper syntax, as stated in the manual is:
if (ctype_alpha(str_replace(array(' ', '', '-'), '', $name)) === false) {
echo'Name must contain letters and spaces only';
exit;
}
With apostrophe
if (ctype_alpha(str_replace(array(' ', '', '-',"'"), '', $name)) === false) {
echo'Name must contain letters and spaces only';
exit;
}
Using '\w' is unfeasible with respect to the apostrophe, i.e. a single quote character. Per the manual:
\w Any word character (letter, number, underscore)
As for the syntax in the OP's code, the primary issue is needing to have an array of characters for the first parameter of str_replace() in order to replace multiple characters.
In addition to enclosing a single quote in double quotes ("'"), PHP permits escaping the single quote character with a backslash and then enclosing it in single quotes, as the following snippet indicates:
<?php
$name = "Kate O'Henry-Smith";
$arrDelChars = [' ','\'','-'];
if ( ctype_alpha( str_replace( $arrDelChars, '', $name ) ) === false ) {
exit( "Name must contain letters and spaces only\n" );
}
print_r($name);
See demo
str_replace() replaces each character in $name with an empty string based on an array of values to exclude. Note, specifying the empty string in the array is needless since the replacement value is the empty string. The new string which emerges becomes the actual parameter for ctype_alpha() instead of $name. Accordingly the function returns true. Consequently, the if-conditional evaluates as false, thereby preventing an error message from displaying. Cute trick for allowing ctype_alpha() to validate $name so-to-speak.
I have the following PHP code:
$search = "foo bar que";
$search_string = str_replace(" ", "|", $search);
$text = "This is my foo text with qué and other accented characters.";
$text = preg_replace("/$search_string/i", "<b>$0</b>", $text);
echo $text;
Obviously, "que" does not match "qué". How can I change that? Is there a way to make preg_replace ignore all accents?
The characters that have to match (Spanish):
á,Á,é,É,í,Í,ó,Ó,ú,Ú,ñ,Ñ
I don't want to replace all accented characters before applying the regex, because the characters in the text should stay the same:
"This is my foo text with qué and other accented characters."
and not
"This is my foo text with que and other accented characters."
The solution I finally used:
$search_for_preg = str_ireplace(["e","a","o","i","u","n"],
["[eé]","[aá]","[oó]","[ií]","[uú]","[nñ]"],
$search_string);
$text = preg_replace("/$search_for_preg/iu", "<b>$0</b>", $text)."\n";
$search = str_replace(
['a','e','i','o','u','ñ'],
['[aá]','[eé]','[ií]','[oó]','[uú]','[nñ]'],
$search)
This and the same for upper case will complain your request. A side note: ñ replacemet sounds invalid to me, as 'niño' is totaly diferent from 'nino'
If you want to use the captured text in the replacement string, you have to use character classes in your $search variable (anyway, you set it manually):
$search = "foo bar qu[eé]"
And so on.
You could try defining an array like this:
$vowel_replacements = array(
"e" => "eé",
// Other letters mapped to their other versions
);
Then, before your preg_match call, do something like this:
foreach ($vowel_replacements as $vowel => $replacements) {
str_replace($search_string, "$vowel", "[$replacements]");
}
If I'm remembering my PHP right, that should replace your vowels with a character class of their accented forms -- which will keep it in place. It also lets you change the search string far more easily; you don't have to remember to replaced the vowels with their character classes. All you have to remember is to use the non-accented form in your search string.
(If there's some special syntax I'm forgetting that does this without a foreach, please comment and let me know.)
I'm trying to replace all of the consecutive spaces with just one underscore; I can easily replace one space with "_" by using the following line of code:
str_replace(" ", "_",$name);
Evan I can replace one spaces with "_" by following line of code:
str_replace(" ", "_",$name);
But the problem is I don't know how many blank spaces I have to check!
If my question is not clear please let me know which part you need more clarification.
Thanks
Probably the cleanest and most readable solution:
preg_replace('/[[:space:]]+/', '_', $name);
This will replace all spaces (no matter how many) with a single underscore.
You can accomplish this with a regular expression:
[ ]+
This will match "one or more space characters"; if you want "any whitespace" (including tabs), you can instead use \s+.
Using this with PHP's preg_replace():
$name = preg_replace('/[ ]+/', '_', $name);
Use preg_replace():
$name = preg_replace('/ +/', '_', $name);
+ in regex means "repeated 1 or more times" hence this will match [SPACE] as well as [SPACE][SPACE][SPACE].
You can use regular expressions:
$name = preg_replace("#\s+#", "_", $name);
I am trying to verify in PHP with preg_match that an input string contains only "a-z, A-Z, -, _ ,0-9" characters. If it contains just these, then validate.
I tried to search on google but I could not find anything usefull.
Can anybody help?
Thank you !
Use the pattern '/^[A-Za-z0-9_-]*$/', if an empty string is also valid. Otherwise '/^[A-Za-z0-9_-]+$/'
So:
$yourString = "blahblah";
if (preg_match('/^[A-Za-z0-9_-]*$/', $yourString)) {
#your string is good
}
Also, note that you want to put a '-' last in the character class as part of the character class, that way it is read as a literal '-' and not the dash between two characters such as the hyphen between A-Z.
$data = 'abc123-_';
echo preg_match('/^[\w|\-]+$/', $data); //match and output 1
$data = 'abc..';
echo preg_match('/^[\w|\-]+$/', $data); //not match and output 0
You can use preg_replace($pattern, $replacement, $subject):
if (preg_replace('/[A-Za-z0-9\-\_]/', '', $string)) {
echo "Detect non valid character inside the string";
}
The idea is to remove any valid chars, if the result is NOT empty do the code.
I'm making a form that asks for the user's first and last name, and I don't want them entering
$heil4
I would like them to enter
Sheila
I know how to filter out everything except letters, but I'm aware that some names can have
Sheila-McDonald
So how would I remove everything from a string apart from letters and a hyphen?
Simply use
$s = preg_replace("/[^a-z-]/i", "", $s);
or if you want to convert some non-ascii characters to ascii, such as Jean-Rémy to Jean-Remy, then use
$s = preg_replace("/[^a-z-]/i", "", iconv('UTF-8', 'ASCII//TRANSLIT//IGNORE', $s));
Instead of replacing with nothing, have some fun. that way a name that consists mainly of numbers you can decode ;p
$name = '$h3il4-McD0nald';
$find = array(0,1,3,4,5,6,7,'$');
$replace = array('o','l','e','a','s','g','t','s');
$name = str_replace($find,$replace,$name);
//Sheila-McDonald
echo ucfirst(preg_replace('/[^a-z-]/i', '', $name));
$new = preg_replace('#[^A-Z-]#iu', '', $data);
but instead of removing letters (and thus modifying user's input) better validate it
and show an error if the input is not valid. This way the user will know that what he had entered is exactly the value you have
if(!preg_match('#[A-Z-]#iu', $data)) echo 'invalid';
Use this to strip out all non alpha-numeric characters, not including non latin characters, and prescribed punctuation.
$strtochange= preg_replace("/[^\s\p{Pd}a-zA-ZÀ-ÿ]/",'',$strtochange);
Note: this will turn $heil4 into heil.