views:

52

answers:

3

How to search text usign php ?

I means :

<?php

$text ="hello World!";

if ($text contains "world") {
echo "True";
}

?>
+4  A: 

In your case you can just use strpos(), or stripos() for case insensitive search:

if (stripos($text, "world") !== false) {
    echo "True";
}
BoltClock
+2  A: 

What you need is strstr()(or stristr(), like LucaB pointed out). Use it like this:

if(strstr($text, "world")) {/* do stuff */}
Gabi Purcaru
strpos or stripos is better for the use case given by the OP - strstr goes to all the trouble of constructing a new string, only to be thrown away...
Paul Dixon
Adding to Paul's comment, from the PHP manual for [`strstr()`](http://www.php.net/manual/en/function.strstr.php): "If you only want to determine if a particular needle occurs within haystack, use the faster and less memory intensive function `strpos()` instead."
BoltClock
Well actually, it's an unreasonable microoptimization to use strpos over strstr given the original example. The returned string goes to waste, but basing the decision on 'performance' for a *single* text search doesn't seem sensible.
mario
A: 

This might be what you are looking for:

<?php

$text = 'This is a Simple text.';

// this echoes "is is a Simple text." because 'i' is matched first
echo strpbrk($text, 'mi');

// this echoes "Simple text." because chars are case sensitive
echo strpbrk($text, 'S');
?>

Is it?

Or maybe this:

<?php
$mystring = 'abc';
$findme   = 'a';
$pos = strpos($mystring, $findme);

// Note our use of ===.  Simply == would not work as expected
// because the position of 'a' was the 0th (first) character.
if ($pos === false) {
    echo "The string '$findme' was not found in the string '$mystring'";
} else {
    echo "The string '$findme' was found in the string '$mystring'";
    echo " and exists at position $pos";
}
?>

Or even this

<?php
$email  = '[email protected]';
$domain = strstr($email, '@');
echo $domain; // prints @example.com

$user = strstr($email, '@', true); // As of PHP 5.3.0
echo $user; // prints name
?>

You can read all about them in the documentation here:

http://php.net/manual/en/book.strings.php

Trufa