Bruce
Bruce

Reputation: 35265

String tokenizer for PHP

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.

Upvotes: 1

Views: 5147

Answers (3)

Hanseh
Hanseh

Reputation: 717

You can also use strstr

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

Upvotes: 0

Dumb Guy
Dumb Guy

Reputation: 3446

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(" ");
}
?> 

Upvotes: 5

Jacob Relkin
Jacob Relkin

Reputation: 163248

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
}

Upvotes: 3

Related Questions