开发者

Scan HTML for values with a special character before them

Say I have values on my page, like #100 #246, What I want to do is scan the page for values with a # before them and then alter them to put a hyperlink on it

$MooringNumbers = '#!' . $MooringNumbers . ' | ' . '#!' . $row1["Number"];
  }  
    $viewedResult =  '<tr><td>' .$Surname.'</td><td>'.$Title.'</td><td>'.$MooringNumbers . '</td><td>'.$Telephone.'</td><td>' . '<a href="rlayCustomerUpdtForm.php?id='.$id.'">[EDIT]</a></td>'.'<td>'. '<a href="deleteCustomer.php?id='.$id.'">[x]</a></td>'. '</tr>';  开发者_如何学C preg_replace('/#!(\d\d\d)/', '<a href="update.php?id=${1}">${1}</a>', $viewedResult);
    echo $viewedResult;

This is the broken code which doesnt work.


I second Xoc - use PHP manual. The method next to the one he pointed is preg-replace-callback

Just call:

preg_replace_callback(
        '/#\d\d\d/',
        create_function(
            // single quotes are essential here,
            // or alternative escape all $ as \$
            '$matches',
            'return strtolower($matches[0]);' //this you replace with what you want to fetch from database
        )

EDIT: Since you want to always perform the same replacement go with Xoc's preg-replace:

preg_replace('/#!(\d\d\d)/', '<a href="update.php?id=${1}">${1}</a>', $your_input);

Note: I don't have PHP here, so I give no guarantee of this code not wiping your entire hard disk ;)


You can accomplish this by using regular expressions, see PHP's preg_replace function.

$text = 'Lorem ipsum #300 dolar amet #20';

preg_match_all('/(^|\s)#(\w+)/', $text, $matches);

// Perform you database magic here for each element in $matches[2]
var_dump($matches[2]);

// Fake query result
$query_result = array ( 300 => 'http://www.example1.com', 20 => 'http://www.example2.com');

foreach($query_result as $result_key => $result_value)
{
    $text = str_replace('#'.$result_key, '<a href="'.$result_value.'">'. $result_value . '</a>', $text);
}

var_dump($text);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜