Page 3 of 3

Posted: Wed Apr 04, 2007 6:04 pm
by Sinemacula
Somehow, I missed this part of your post...
Everah wrote:You really can't do anything about it without knowing where it is or going after it in some capacity :wink:. You can use regexp or you can use strpos() if you know there will only be one colon in the string.
I guess the issue is that I don't really need to know where it is, or if there is more than one ":" -- I just need to be able to get at everything that precedes the ":" -- so using

Code: Select all

$precolon = explode(":", $books[2]);
and then just using $precolon[0] where I need the string works okay... so, the question is whether strpos() is a better way to do it, and if so, how to make it work for getting all text before a given character?

Looking on the manual page for strpos() there are examples for getting text from between two strings... would I take that sort of approach and just use -1 as the starting position and ":" as the ending string?

Posted: Wed Apr 04, 2007 6:24 pm
by RobertGonzalez
substr() and strpos() play well together for things like this. But if you are into using explode() do it if your are comfortable with it.

Posted: Wed Apr 04, 2007 7:05 pm
by Sinemacula
Everah wrote:substr() and strpos() play well together for things like this. But if you are into using explode() do it if your are comfortable with it.
I decided to give using strpos() and substr() a shot...

Here's what I've tried:

Code: Select all

$pos = strpos($books[2],":");
$searchbooks = substr($books[2],0,$pos);
It works great for when the $books[2] string has a ":" in it, but doesn't work if there's no ":".

So, to make this work, it seems like I'd need an if statement, making it:

Code: Select all

$pos = strpos($books[2],":");
if ($pos > 0) 
{
	$searchbooks = substr($books[2],0,$pos);
} else {
	$searchbooks = $books[2];
}
...which appears to work (although I think I'm still going to need to remove the parentheses as having the url encoded parentheses is interfering with the search results).

So, is there any performance or other benefit to doing it this way rather than explode()?

Posted: Wed Apr 04, 2007 11:22 pm
by RobertGonzalez

Code: Select all

<?php
if (($pos = strpos($books[2],":")) !== false) {
        $searchbooks = substr($books[2],0,$pos);
} else {
        $searchbooks = $books[2];
}
?>
I have never done speed comparisons on explode() versus strpos()/substr(). I do know that the string functions are very fast.