finding a substring inside a string

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
dsdsdsdsd
Forum Commoner
Posts: 60
Joined: Fri Dec 05, 2003 3:10 pm

finding a substring inside a string

Post by dsdsdsdsd »

hello;

I would like to determine if substring exists within a string;

$substring = 'poiuy';
$string='_okmn_wwwwwww_poiuy_asasasasas';

is $substring inside of $string?

thank you
Shannon Burnett
User avatar
mudkicker
Forum Contributor
Posts: 479
Joined: Wed Jul 09, 2003 6:11 pm
Location: Istanbul, TR
Contact:

Post by mudkicker »

[php_man]ereg[/php_man] function or [php_man]substr_count[/php_man] function would help you.

Code: Select all

<?php
if(substr_count($text,$stringtofind) > 0) {
echo "yes it is in it.";
}

// or

 
if (eregi($stringtofind, $text)) { 
   echo "$text contains - $stringtofind!";
}

?>
qads
DevNet Resident
Posts: 1199
Joined: Tue Apr 23, 2002 10:02 am
Location: Brisbane

Re: finding a substring inside a string

Post by qads »

Code: Select all

<?php
$substring = 'poiuy';
$string='_okmn_wwwwwww_poiuy_asasasasas';
if(strstr($string, $substring))
{
echo 'String was found!';
}
?>
read up: [php_man]strstr[/php_man]
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post by feyd »

User avatar
mudkicker
Forum Contributor
Posts: 479
Joined: Wed Jul 09, 2003 6:11 pm
Location: Istanbul, TR
Contact:

Post by mudkicker »

or strpos() function.
qads
DevNet Resident
Posts: 1199
Joined: Tue Apr 23, 2002 10:02 am
Location: Brisbane

Post by qads »

yep, more then 1 way to skin a cat as they say, you may wanna read up on string functions, just go to [php_man]strstr[/php_man] and you should get all the functions on th left hand side.
dsdsdsdsd
Forum Commoner
Posts: 60
Joined: Fri Dec 05, 2003 3:10 pm

Post by dsdsdsdsd »

I appreciate everyone's responses;

I had looked at these but was swayed away from them because their respective examples were seemingly all discussing single character needles;

I have already started a function that will parse each $string and $substring into arrays, determine first pos in string that matches first character in substring, then determines if all subsequent characters in $string match the subsequent characters in $substring;

I like strpos() better; I should have tested to see if needle could be a multi-character string a couple of hours ago;

thanks
dsdsdsdsd
Post Reply