简体   繁体   中英

preg_match and my string

I would like to have this kind of string:

basically a string of just letters a-zA-Z that can (or cannot) end with à or è or ì or ù.

I did this:

preg_match('/^[a-zA-Z]+[a-zA-Z]+$|^[a-zA-Z]+[àèìòù]?$/', $word)

and I still think is alright but for some reason it doesn't do the job!

EDIT: There are some italian lastname that can end with àèìòù but some other ones just end with a letter. I want to get that the end of the string can end either with àèìòù or with a letter.

this is the full code

if ( preg_match('/^[a-zA-Z]+[àèìòù]?$/', $word) ) {
    echo "0";

} else {
    echo LASTNAME_ERROR;
}

but when I execute it, it gaves me the LASTNAME_ERROR

According to your description I would formulate the regular expression as followed:

/^[a-zA-Z]+[àèìòù]?$/

however from your question it is not clear where exactly your problem is. Your regex looks a bit verbose but not that faulty that it would explain your problem (at least not to me).

Edit: After re-reading your question I see one thing: The variable $word might contain UTF-8 encoded data. If that is the case you need to add the u (PCRE_UTF8) modifier to the regular expression:

/^[a-zA-Z]+[àèìòù]?$/u
                     ^
                     `--- UTF-8 modifier

This is also true the other way round: If you don't use UTF-8 yet for your application but the PHP files are encoded in UTF-8 the regular expression above is not valid, too.

So check the character encoding of both the string and your PHP file, that is one thing I could assume what can go wrong here.

Okay, let's just review some of your Regex, so you can see where you went wrong.

/^[a-zA-Z]+[a-zA-Z]

So one or more a-zA-Z's, followed by an a-zA-Z. Well that's really rather pointless: /^[a-zA-Z]+ would suffice.

^[a-zA-Z]+[àèìòù]?$/

So a-zA-Z one or more times, followed by one or more of your symbols. Well, that's awfully similar to your original regular expression, so let's cut away and put it back together.

/^[a-zA-Z]+[àèìòù]?$/

So we've got a-zA-Z one or more times, followed by the symbols, 0 or more times at the end of the string.

This should be work

/((?!\(à|è|ì|ò|ù)$)[a-zA-Z])+/

(            # start a group for the purposes of repeating
 (à|è|ì|ò|ù) # negative lookahead assertion for the pattern à|è|ì|ò|ù
 [a-zA-Z]    # your own pattern for matching a URL character
)+           # repeat the group

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM