tags:

views:

119

answers:

3

I have used the String Tokenizer in Java. I wish to know if there is similar functionality for PHP. I have a string and I want to extract individual words from it.

eg. If the string is -

Summer is doubtful #haiku #poetry #babel

I want to know if it contains the hashtag #haiku.

+2  A: 

strpos, stripos, strstr, stristr are easy solutions.

strpos example:

$haikuIndex = strpos( $str, '#haiku' ); 
if( $haikuIndex !== FALSE ) {
   // "#haiku" exists
}

strstr example:

$haikuExists = strstr( $str, '#haiku' );

if( $haikuExists !== FALSE ) {
   // "#haiku" exists
}
Jacob Relkin
Aah, I see you have fallen into the old pit. Always compare the result of `strpos` to `=== false`! It's even written in the manual entry you linked to.
deceze
Yeah, it slipped my mind. I've been doing too much Objective-C lately to remember just how loosely typed (read:unpredictable) PHP is.
Jacob Relkin
+1  A: 

You can also use strstr

if (strlen(strstr($str,'#haiku'))>0) { // "#haiku" exists }

Hanseh
From the manual of `strstr`: If you only want to determine if a particular needle occurs within haystack, use the faster and less memory intensive function strpos() instead.
SpawnCxy
+3  A: 

If you want a string tokenizer, then you probably want the strtok function

<?php
$string = "Summer is doubtful #haiku #poetry #babel";
$tok = strtok($string, " ");
while ($tok !== false) {
    if ($tok == "#haiku") {
        // #haiku exists
    }
    $tok = strtok(" ");
}
?> 
Dumb Guy