PHP uses regular expressions to match Chinese, with some solutions that don't match

Source: Internet
Author: User

Today in the development of a need, is to match a price formula in the material text, example: [Goat fat jade prices]*[sheep fat Jade weight]+[Platinum Price]*[Platinum weight]+[opteron price]*[stone weight]+[Diamond price]*1.5*[Diamond weight]+[hard gold price]*1.67*[hard Gold weight], to match out [***_ Price], is within the brackets, to _ Price end of the string (representing the name of the material), I use the language is PHP, Write a regular expression, the code is as follows:

$pattern"/\\[([^_价格]+)_价格\\]/";$res = preg_match_all($pattern$s$matches);var_dump($matches);

, the front three can match out, but the "diamond" has been matched, very strange, after testing a bit, with the number of matches does not matter, because if the "diamond" is also changed to "Platinum" words are able to match out, changed to "stone" word can also be matched out, according to this phenomenon, the feeling may be a character set problem , it is possible that the default character set is not the word "drill", so the match is not, after searching a lot of users about PHP using regular matching Chinese articles, found that the most comprehensive match is the use of 16 binary, after the change, it was successful, so share out, to treat everyone, the final code is as follows:
$s = ' [Goat fat jade price]*[sheep fat Jade weight]+[Platinum Price]*[Platinum weight]+[opteron price]*[stone weight]+[diamond price]*1.5*[diamond weight]+[Hard Gold Price]*1.67*[hard Gold weight] ';

$pattern"/\\[([\x{4e00}-\x{9fa5}]+)_价格\\]/u";$res = preg_match_all($pattern$s$matches);var_dump($matches);

This will be able to extract the goat fat jade/white gold/stone/diamond/hard gold all out

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

PHP uses regular expressions to match Chinese, with some solutions that don't match

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.