Exercise : Show Links

Write a PHP function show_links in showlinks.php that accepts two parameters: an array of URL strings, and a substring to search for. Display each case-insensitively matching link in a div with a bolded numbering in front.

$links = array("http://www.cs.washington.edu/142/", "http://...");
show_links($links, "CS.Washington.Edu");

The call generates this output (see next slide for screenshot):

<h1>Links to CS.Washington.Edu:</h1>
<div>
	<strong>Site #1:</strong>
	<a href="http://www.cs.washington.edu/142/">http://www.cs.washington.edu/142/</a>
</div>
<div> <strong>Site #2:</strong>...</div>

Exercise Example Output

screenshot
show_links($links,
	"CS.Washington.Edu");

Exercise Solution

<?php
function show_links($links, $site) {  # Displays all URLs from the given
	?>                                  # array that match the given site.
	<h1>Links to <?= $site ?>:</h1>
	<?php
	$site = strtolower($site);
	$count = 0;
	foreach ($links as $url) {
		if (strstr($url, $site)) {
			$count++;
			?>
			<div>
				<strong>Site #<?= $count ?>:</strong>
				<a href="<?= $url ?>"> <?= $url ?> </a>
			</div>
			<?php
		}
	}
}
?>