Page 1 of 1

Finding string within string...

Posted: Wed Jul 05, 2006 8:55 pm
by JellyFish
I'm looking for a function that returns true if a specified string contains another specified string.

Example:

Code: Select all

$string = "Sugar and spice and everything nice";

if (TheFunctionI'mlookingfor($string, "spice") {
//true it does contain spice
} else {
//no it really doesn't
}
Thank you for reading.

Posted: Wed Jul 05, 2006 9:05 pm
by Burrito
have a look at strpos()

Posted: Wed Jul 05, 2006 9:30 pm
by JellyFish
mmm. It's not working the way I hoped. Maybe you can give an example of the way you'd do it. I'd really appreciate it. :)

Posted: Wed Jul 05, 2006 9:35 pm
by Benjamin
From the manual...

Code: Select all

<?php
$mystring = 'abc';
$findme  = 'a';
$pos = strpos($mystring, $findme);

// Note our use of ===.  Simply == would not work as expected
// because the position of 'a' was the 0th (first) character.
if ($pos === false) {
   echo "The string '$findme' was not found in the string '$mystring'";
} else {
   echo "The string '$findme' was found in the string '$mystring'";
   echo " and exists at position $pos";
}

// We can search for the character, ignoring anything before the offset
$newstring = 'abcdef abcdef';
$pos = strpos($newstring, 'a', 1); // $pos = 7, not 0
?>

Posted: Wed Jul 05, 2006 9:47 pm
by JellyFish
Oh yes duh. lol.

But this is what I put:

Code: Select all

if (strpos($_GET['name'], '/') === false) {
?>
<script language="JavaScript" type="text/javascript">
	alert("Unable to create. Invalid characters "/" were found in the name specified.");
</script>
<?
} else {
//do what it's suppose to do if the char "/" is not in the $_GET['name']
}
and you see for some reason it doesn't work when I place a "/" in the $_GET['name'] var.

Basically I need a way of checking for invalid characters and if any then use the alert() javascript function. And if it isn't any then do what it's suppose to do.

I'm getting a little confused on this one, I don't know why. :?

Posted: Fri Jul 07, 2006 2:04 pm
by JellyFish
Okay so what I did was this:

Code: Select all

$fix = array("<",">","{","}","[","]",'\"','/'); // a array set up with all of the invalid characters

$name = str_replace($fix,'',$_GET[name]);

if ($_GET['name'] != $name) {
?>
<script language="JavaScript" type="text/javascript">
	alert("Unable to create. Invalid characters <,>,[,],{,},),(,/ were found in the name specified.");
</script>
<?
} else {
It works perfect. If anyone has any other ideas I'm open to suggestion.

Just thought I'd resolve this post for anyone else who has this problem could consider this post as an reasonable method.

Posted: Fri Jul 07, 2006 2:22 pm
by Burrito
I believe you can use a 'mixed' type in strpos() as well...ohwell whatever works.