Page 1 of 1

Replace list of words with associated links

Posted: Sun Dec 03, 2006 5:05 pm
by danthemightyone
I have a list of words and corresponding links eg.

dog http://www.bigdog.com

cat http://www.nicecat.com

fox http://www.fox.com

Can I have one regular expression that will replace all the words on the left hand side of the list (ie. dog, cat, fox) with the left hand side (http://www.bigdog.com, http://www.nicecat.com, http://www.fox.com)?

Lets take an input string:

The dog saw the cat and fox laughing.

I want the output to be:

The <a href="http://www.bigdog.com">dog</a> saw the <a href="http://www.nicecat.com">cat</a> and <a href="http://www.fox.com">fox</a> laughing.

I will take the word/link list as xml eg;

<masterlist>
<keyword>
<text>dog</text>
<url>http://www.bigdog.com</url>
</keyword>
<keyword>
<text>cat</text>
<url>http://www.nicecat.com</url>
</keyword>
<keyword>
<text>fox</text>
<url>http://www.fox.com</url>
</keyword>
</masterlist>

I am also using msxsl c# script for the reular expression.

Can anyone help me please?

Posted: Sun Dec 03, 2006 5:33 pm
by feyd
You'll need something like preg_replace_callback() for that.

Posted: Mon Dec 04, 2006 9:45 am
by Corvin
You can do that this way:

Code: Select all

<?php
// xml to array
include "xmltoarray.php";
$xml = file_get_contents("list.xml");
$xmlObj = new XmlToArray($xml);
$list = $xmlObj->createArray();

// modify array from $list['masterlist']['keyword']['x']['text'] to $list['[text]']
$list2 = array();
for ($i=0;$i<count( $list['masterlist']['keyword'] );$i++) {
	$text = $list['masterlist']['keyword'][$i]['text'];
	$list2[$text] = $list['masterlist']['keyword'][$i]['url'];
}

$list = $list2;

// replace ..
$text = "The dog saw the cat and fox laughing.";

foreach($list as $key => $value) {
	$text = str_replace($key, "<a href=\"".$value."\">".$key."</a>", $text);
}

// print ..
echo $text;
?>
I used this class for that.

Posted: Mon Dec 04, 2006 5:51 pm
by danthemightyone
That works great thanks a lot :D