searching the 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
dibyendra
Forum Newbie
Posts: 20
Joined: Tue Aug 12, 2003 2:26 am
Location: Nepal

searching the string

Post by dibyendra »

Hi there,
I want to check the user submitted text phrase for certain words.how can I search the certain word in that submitted strting and highlight the found word?
Please suggest me
thanking you
Dibyendra
User avatar
volka
DevNet Evangelist
Posts: 8391
Joined: Tue May 07, 2002 9:48 am
Location: Berlin, ger

Post by volka »

not quite sure what you're looking for this might help

Code: Select all

<html>
	<head>
		<style type="text/css">
			.highlight { background-color: silver; }
		</style>
	</head>
	<body>
		<pre>
<?php
	if(isset($_POST['text']))
	{
		$display = htmlentities($_POST['text']);
		if(isset($_POST['hilight']))
		{
			$search = htmlentities($_POST['hilight']);
			$display = str_replace($search, '<span class="highlight">'.$search.'</span>' ,$display);
		}
		echo $display;
	}
?>
		</pre>
		<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>" >
			<label for="text1">text:</label><textarea name="text" id="text1" ></textarea>
			<br />
			<label for="hilight1">highlight:</label><input type="text" name="hilight" id="hilight1" >
			<br />
			<input type="submit" />
		</form>
	</body>
</html>
if(isset($_POST['hilight']))
{
$search = htmlentities($_POST['hilight']);
$display = str_replace($search, '<span class="highlight">'.$search.'</span>' ,$display);
}
this replaces all occurences of the search pattern by the search pattern encapsulated by <span>-element.
The element's class is styled to have grey background color
Post Reply