7

How can I add/improvised my code so Spanish accent will be considered as valid in addition to normal alphabet (a-z)

I have the following in my code

public static function IsAlpha($s){
  $reg = "#[^a-z\s-]#i";
  $count = preg_match($reg, $s, $matches);
  return $count == 0;
}
xar
  • 1,429
  • 2
  • 17
  • 29
  • 3
    Potentially duplicate question has the answer: [PHP: PREG: How to match special chars like a grave?](http://stackoverflow.com/questions/2133758/php-preg-how-to-match-special-chars-like-a-grave) – Wiseguy Nov 22 '11 at 14:22
  • It's a similar question, however, I still can't figure out how to integrate it with my existing regex. – xar Nov 22 '11 at 14:36
  • 1
    @Wiseguy: you should post this comment as an answer. – Toto Nov 22 '11 at 14:45

3 Answers3

23

As found in the answer to this question, you could match accented characters using the full Letter Unicode property \p{L}. That includes regular a-z characters along with accented ones, so replace a-z in your expression with this like so:

$reg = "#[^\p{L}\s-]#u";

Note that to use this you need the UTF-8 modifier u after your closing delimiter, as the docs say such Unicode "character types are available when UTF-8 mode is selected".

Community
  • 1
  • 1
Wiseguy
  • 20,522
  • 8
  • 65
  • 81
1

I think you can use the hexadecimal representation of each letter:

<?php
function IsAlpha($sString)
{

  $reg = "#[a-zA-Z\xE1\xE9\xED\xF3\xFA\xC1\xC9\xCD\xD3\xDA\xF1\xD1]+#i";
  $count = preg_match_all($reg, $sString, $matches, PREG_OFFSET_CAPTURE);
  return $matches;
}
echo '<pre>';
print_r(IsAlpha("abcdefgh ñ á é í ño 123 asd asáéío nmas asllsdasd óúfl ÑABDJÓ ÚñÍÉ"));
echo '</pre>';

I do not know if there are all the letters, but you can add more with this link.

Galled
  • 4,146
  • 2
  • 28
  • 41
0

You can also use T-Regx:

pattern('[^\p{L}\s-]', 'u')->fails($s);
Danon
  • 2,771
  • 27
  • 37