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?
Replace list of words with associated links
Moderator: General Moderators
-
danthemightyone
- Forum Newbie
- Posts: 4
- Joined: Sun Dec 03, 2006 4:42 pm
- feyd
- Neighborhood Spidermoddy
- Posts: 31559
- Joined: Mon Mar 29, 2004 3:24 pm
- Location: Bothell, Washington, USA
You'll need something like preg_replace_callback() for that.
You can do that this way:
I used this class for that.
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;
?>-
danthemightyone
- Forum Newbie
- Posts: 4
- Joined: Sun Dec 03, 2006 4:42 pm