/    Sign up×
Community /Pin to ProfileBookmark

strpos( )!?

Hi!

This script searches for the varaibles $search_string in a string. The problem is that if the search string contains text that is present in the first charater of the string then it still returns a negative result as the position is ‘0’

[code=php]
<?php
$my_string=”This is a string”;
$search=”This”;
if(strpos($my_string,$search))
echo “Found string”;
else
echo “Aww no string present”;

?>
[/code]

how would i get around this.

Thank-you.

to post a comment
PHP

3 Comments(s)

Copy linkTweet thisAlerts:
@solavarJun 15.2004 — This is a tricky one.

Try...

[code=php]
<?php
$my_string="This is a string";
$search="This";
$strpos = strpos($my_string,$search);


if($strpos === FALSE) // note the use of 3 equal signs
{
// We know string was definitely not found;
echo "Aww no string found!";

}
else
{
echo "String was found at position $strpos";

}
?>
[/code]
Copy linkTweet thisAlerts:
@shimonJun 15.2004 — strpos isn't really the logical function to use here though. stristr mayb be better since it returns a proper FALSE if no match is found. Try this (and remember to use braces properly):

[code=php]<?php

$my_string = "This is a string";
$search = "This";

if (stristr($my_string, $search)) {
echo "Found string";
} else {
echo "Aww no string present";
}

?>[/code]


n.b. stristr() is case-insensitive, you could use strstr() if you want case-sensitive matching
Copy linkTweet thisAlerts:
@NaemoauthorJun 15.2004 — Thank-you!
×

Success!

Help @Naemo spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 5.28,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @AriseFacilitySolutions09,
tipped: article
amount: 1000 SATS,

tipper: @Yussuf4331,
tipped: article
amount: 1000 SATS,

tipper: @darkwebsites540,
tipped: article
amount: 10 SATS,
)...