Compare two strings in PHP to find the first example of a different character position

Source: Internet
Author: User

  This is a problem on the StackOverflow. gives two strings of equal length, finding the first different character position in the two strings.

The general practice is this: the     code is as follows: <?php for ($offset = 0; $offset < $length; + + $offset) {    if ($str 1[$offs ET]!== $str 2[$offset]) {        return $offset    }} The best answer given below is a different or an operator (^) that has never been used before. Operators, do not know where to use, today is learned.   Because in general, when you vary or manipulate two strings, the same character's XOR or result is null (""), so we just need to find the first non-null ("") character.     Code as follows: <?php $position = strspn ($string 1 ^ $string 2, ""); Obviously this is a more elegant and efficient method. In addition, the answering person also attaches a multibyte character solution. The code is as follows: <?php function getcharacteroffsetofdifference ($str 1, $str 2, $encoding = ' UTF-8 ') {    return Mb_strlen ($str 1, $encoding)            -Mb_strlen (                 mb_strcut (                      $STR 1,     & nbsp                STRSPN ($str 1 ^ $str 2, ""),           &NBSP ;          mb_stRlen ($str 1, ' 8bit '),                       $encoding     & nbsp            ,                   $encoding              ); }  

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.