Skip to content
Advertisement

Apostrophe issues with preg_match

Hi first time question here … I have the following pattern for preg_match that isn’t working, which I have learnt may be an UTF-8 encoding issue … or just my bad coding!

The following pattern works, but not for the apostrophe (with/without escaping the apostrophe makes no difference):

$pattern="/^([A-Za-z '-])+$/";

The following pattern works for the apostrophe like I want it to, but it also allows the &, # and ; which is not ideal:

$pattern="/^([A-Za-z '-])+$/";

This pattern works properly for all characters, however only allows one instance of the apostrophe in the input text string (and I don’t understand the significance of 0* in the &#0*39;):

$pattern="/^([A-Za-z -])+('|&#0*39;)*([A-Za-z -])+$/";

Can anyone shed light on where I’m going wrong? I have literally been through a hundred pages looking for an answer and it’s driving me crazy!

Advertisement

Answer

How about:

$pattern="/^([A-Za-z -]+(?:'|&#0*39;)*)*[A-Za-z -]+$/";
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement