PHP - Searching Strings with strstr()

Introduction

To find out whether some text occurs within a string, use strstr().

This function takes two parameters: the string to search through, and the search text.

If the text is found, strstr() returns the portion of the string from the start of the found text to the end of the string.

If the text isn't found, it returns false. For example:

Demo

<?php

$myString = "Hello, world!";
echo strstr( $myString, "wor" ) . " \n ";                   
echo ( strstr( $myString, "xyz" ) ? "Yes" : "No" ) . " \n "; 

?>/*from w ww .jav a  2  s.co  m*/

Result

You can pass an optional third Boolean argument.

The default value is false.

If you pass in a value of true, strstr() returns the portion from the start of the string to the character before the found text:

Demo

<?php
$myString = "Hello, world!";
echo strstr( $myString, "wor", true );
?>//w  w w. ja  v a 2  s.  c  o  m

Result

Related Topic