For my stock-market chat I want to replace every specific string pattern to html code. For example if I type "b $goog 780" i want this string to be replaced with:
Buy <a href="/stocks/goog">$goog</a> at 780
How can I do this specific task with preg_replace?
$cmd='b $goog 780';
if(preg_match('/^([bs])\s+?\$(\w+?)\s+?(.+)$/i',$cmd,$res))
{
switch($res[1])
{
case 'b': $cmd='buy';break;
case 's': $cmd='sell';break;
}
$link=$cmd.' <a href="/stocks/'.$res[2].'">'.$res[2].'</a> at '.$res[3];
echo $link;
}
$stocks = array('$goog' => '<a href="/stocks/goog">$goog</a>',
'$apple' => '<a href="/stocks/apple">$apple</a>');
// get the keys.
$keys = array_keys($stocks);
// get the values.
$values = array_values($stocks);
// replace
foreach($keys as &$key) {
$key = '/\b'.preg_quote($key).'\b/';
}
// input string.
$str = 'b $goog 780';
// do the replacement using preg_replace
$str = preg_replace($keys,$values,$str);
Does it have to be preg_replace? Using preg_match you can extract the components of the string and recombine them to form your link:
<?php
$string = 'b $goog 780';
$pattern = '/(b \$([^\s]+) (\d+))/';
$matches = array();
preg_match($pattern, $string, $matches);
echo 'Buy <a href="/stocks/' . $matches[2] . '">$' . $matches[2] . '</a> at ' . $matches[3] ; // Buy <a href="/stocks/goog">$goog</a> at 780
What the pattern is looking for, is the letter 'b', followed by a dollar symbol (\$
- we escape the dollar as this is a special character in regex), then any and every character until it gets to a space ([^\s]+
), then a space, and finally any number of numbers (\d+
).