Example of php determining whether a string contains another string

Source: Internet
Author: User

Example. Explode

The code is as follows: Copy code

Function checkstr ($ str ){
$ Needle = "B"; // determines whether the string contains.
$ Tmparray = explode ($ needle, $ str );
If (count ($ tmparray)> 1 ){
Return true;
} Else {
Return false;
 }
}

The principle is very simple: it is to define the characters we are looking for, and then we use explode to divide them into functions, if the split is successful and the array length is greater than 1, no code exists. You need to find the character. Otherwise, no code exists. This is only applicable to determining whether the character in the string exists, A deeper layer will not work.

Example: strpos ()

The strpos () function returns the position where the string first appears in another string.

The code is as follows: Copy code

<? Php
$ Attach = 'Mr/online/php/img/news /';
// Be sure to use it! =
// The string to be searched returns 0 at the first position
If (strpos ($ attach, 'Mr/online ')! = False ){
// If omr/online is included
   }
?>

Example: strstr ()

The strstr () function searches for the first occurrence of a string in another string.

The code is as follows: Copy code

<? Php
$ Attach = 'Mr/online/php/img/news /';
// Be sure to use it! =
// Return the rest of the string (from the matching point)
If (strstr ($ attach, 'Mr/online ')! = False ){
// If omr/online is included
   }
?>

Summary

I think the simplest is strpos ($ a, $ B )! = False if $ B exists in $ a, true is used; otherwise, false is used.

Yes! = False (or = false) is because if $ B is located at the beginning of $ a, the function returns int (0), and 0 is false, but $ B does exist in $ a, so use it! = Determine the type. Make sure that it is strictly false. I went to Zhongguancun library building last night and saw a book using strpos = true. This is extremely incorrect.

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.