Sunday, April 7, 2013

Php Convert String Specific Words To Links In Paragraphs.

Php Convert String Specific Words Within Paragraphs Into Links. This little jewel allows you to do some sneaky self made tags within your blog or forum. Can be used before input or even better on coming out of the database query. The thing to remeber is that arrays are mirrored within preg_replace and require the $replacements variables to be in numeric reverse order. If you add another to the list it will be $items[3] and the new $replacements var will become [0] which moves the replacements up one numeric order. This would place shoes replacement at [3] shirts at [2] and jeans at[1] then new item var at [0].

$string = 'She has shirts in blue her jeans in black and her shoes are all faded.';
$items = array();
$items[0] = '/shoes/'; //List of items you want changed//
$items[1] = '/shirts/';
$items[2] = '/jeans/';
$replacements = array();
$replacements[2] = 'a href="">Shoes /a>';
$replacements[1] = 'a href="index.php?items=shirts">Shirts /a>';
$replacements[0] = 'a href="index.php?items=jeans">Jeans /a>';
$output = preg_replace($items, $replacements, $string);

Outputs: The paragraph and links on the selected items.

No comments:

Post a Comment