如何在preg_match_all正则表达式中支持单引号匹配
The issue you’re hitting comes down to how PHP handles single quotes in string literals. Since your regex is wrapped in a single-quoted PHP string, adding an unescaped ' inside would terminate the string early, causing a syntax error—that’s why your first attempt failed. When you tried \', that’s the right approach for single-quoted strings (PHP interprets \' as a literal single quote), but it sounds like you might have placed it incorrectly or ran into a formatting quirk.
Here’s the modified regex with proper single quote support added to the character class:
preg_match_all('@[A-z0-9 ./\'áàâäãåǻăāąấấặắǎȧạàãáćĉċčççďđḑḋḍdéèêëĕěēęėềẽȩẹéĝğġģǧǵḡĥħȟḣḥḩíìîïĭїĩīįǐĪỊ̣iỊǏĨị̣ịıíĵ ķǩḱḳļľŀĺĺóòôöõðőŏōỏǒǫȯoøồớòóõöñńņňʼnŋǹṅṇŕŗřṙṛśŝşšṡṣşșţťŧțṫṭtúùûüůūűųũŭǔǘǚǜụuưüúŵ ŷýÿўỹẏỳỵyẙȳẙźżžẑẓḅḟḿṁṃṕṗṽṿḷẁẃẅẉẘẘẋẍÒÓÔÕÖŐǑǪŌȮØÙÚÛǓǗǙǛŨŮŰŲÜỤŪĆĈČÇÀÁÂÃÄÅẠĄĀȦǍ ÈÉÊËĖĘĚẸẼĒȨḾṀṂŚŜŞŠṠṢŹŻŽẐẒŃŅŇṄṆÑǸḢḤḨĤȞĹĻĽĿŢŤṪṬŖŘṘṚĜĠĢǦǴḠẀẂẄẈŴḊḌḐĎĐÐṔṖĶǨḰḲẊẌ ṼṾỴỸỲẎŸȲŶÝĴȷḄḞḶŁłÏÎÍÌıİßıs-]+#[^#]+@', $matches, $countries);
I added \' right after the space in the opening character class ([A-z0-9 ./\'...). This tells PHP to treat the ' as a literal character in the regex, not as the end of the string.
If you prefer a more readable alternative, you can use two single quotes ('') to represent a literal single quote in the PHP string—this works just as well:
preg_match_all('@[A-z0-9 ./''áàâäãåǻăāąấấặắǎȧạàãáćĉċčççďđḑḋḍdéèêëĕěēęėềẽȩẹéĝğġģǧǵḡĥħȟḣḥḩíìîïĭїĩīįǐĪỊ̣iỊǏĨị̣ịıíĵ ķǩḱḳļľŀĺĺóòôöõðőŏōỏǒǫȯoøồớòóõöñńņňʼnŋǹṅṇŕŗřṙṛśŝşšṡṣşșţťŧțṫṭtúùûüůūűųũŭǔǘǚǜụuưüúŵ ŷýÿўỹẏỳỵyẙȳẙźżžẑẓḅḟḿṁṃṕṗṽṿḷẁẃẅẉẘẘẋẍÒÓÔÕÖŐǑǪŌȮØÙÚÛǓǗǙǛŨŮŰŲÜỤŪĆĈČÇÀÁÂÃÄÅẠĄĀȦǍ ÈÉÊËĖĘĚẸẼĒȨḾṀṂŚŜŞŠṠṢŹŻŽẐẒŃŅŇṄṆÑǸḢḤḨĤȞĹĻĽĿŢŤṪṬŖŘṘṚĜĠĢǦǴḠẀẂẄẈŴḊḌḐĎĐÐṔṖĶǨḰḲẊẌ ṼṾỴỸỲẎŸȲŶÝĴȷḄḞḶŁłÏÎÍÌıİßıs-]+#[^#]+@', $matches, $countries);
Either version will now correctly match strings containing single quotes like your example: This - is Mary's phone (assuming it’s part of a larger string that fits your regex pattern with the # delimiters).
内容的提问来源于stack exchange,提问作者mary ongubo

