PHP strpos() Help

tooltiperror

Super Moderator
Reaction score
231
Gah, I can't figure this out.

PHP:
<?php

$poop = "  Print  ";

function HighlightWord($word)
{
	if (strpos($poop, ' '.$word.' ') !== false)
	{
		return 'It works...';
	}
	return $word;
}

echo HighlightWord('Print');

?>

I can't figure out why it doesn't print "It Works..." :confused:
 

Lyerae

I keep popping up on this site from time to time.
Reaction score
105
PHP:
<?php 

$data1 = "   HELLO   ";

function HighlightWord($word, $data)
{
	if (strpos($data, ' ' . $word) != false) 
		return "It works!";
	
	return $word;
}

echo HighlightWord('HELLO', $data1);


?>

That works for me (awesome variable names you have thar.).
 

tooltiperror

Super Moderator
Reaction score
231
But can you tell me why that script doesn't work?
 

Lyerae

I keep popping up on this site from time to time.
Reaction score
105
It told me that $data1 was not defined until I passed it as an argument, so I'd say an issue with scoping.
 

tooltiperror

Super Moderator
Reaction score
231
Ah, got it. I forgot [LJASS]global $poop;[/LJASS]. Derp is me, I did it in my other function too? Gosh.

+Reputation :)
 

Magentix

if (OP.statement == false) postCount++;
Reaction score
107
Instead of using a global, why not add it as a parameter?

PHP:
function HighlightWord($needle, $haystack) {
    if (strpos($haystack, ' ' . $needle . ' ') !== false) return "It works!";
}

echo HighlightWord('HELLO', 'Why HELLO thar, sailor!');

Edit: Also, have a look at preg_match for this. The word boundary (\b) will help you a lot more than checking for a space before and after a match.
 
General chit-chat
Help Users
  • No one is chatting at the moment.

      The Helper Discord

      Staff online

      Members online

      Affiliates

      Hive Workshop NUON Dome World Editor Tutorials

      Network Sponsors

      Apex Steel Pipe - Buys and sells Steel Pipe.
      Top