Compare two strings in PHP to find the first character location. example _ PHP Tutorial

Source: Internet
Author: User
In PHP, compare two strings to find the first character location. The general practice is as follows: Copy the code as follows :? Phpfor ($ offset0; $ offset $ length; ++ $ offset) {if ($ str1 [$ offset]! $ Str2 [$ offset]) {return $ offset;} The general practice is as follows:

The code is as follows:


For ($ offset = 0; $ offset <$ length; ++ $ offset ){
If ($ str1 [$ offset]! ==$ Str2 [$ offset]) {
Return $ offset;
}
}


The best answer to the question below is the use of an exclusive or operator (^). I have never used this operator before, and I do not know where to use it. I learned it today.

Generally, when you perform an exclusive or operation on two strings, the exclusive or result of the same character is null ("\ 0 "), so we only need to find the first non-null ("\ 0") character.

The code is as follows:


$ Position = strspns ($ string1 ^ $ string2, "\ 0 ");


Obviously, this is a more elegant and efficient method. In addition, the answer is appended with a multi-byte character solution.

The code is as follows:


Function getCharacterOffsetOfDifference ($ str1, $ str2, $ encoding = 'utf-8 '){
Return mb_strlen ($ str1, $ encoding)
-Mb_strlen (
Mb_strcut (
$ Str1,
Strspns ($ str1 ^ $ str2, "\ 0 "),
Mb_strlen ($ str1, '8bit '),
$ Encoding
),
$ Encoding
);
}

The pipeline code is as follows :? Php for ($ offset = 0; $ offset $ length; ++ $ offset) {if ($ str1 [$ offset]! ==$ Str2 [$ offset]) {return $ offset...

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.