语言:PHP
我有一个自定义标签的文本字符串,如下所示:
text text <mention userid="1" username="Jack Smith"> text text
我不太擅长正则表达式,所以我真的不知道如何:
1) 提取所有提到的ID和用户名
2) 将提及内容替换为NAME
所以,基本上我需要这样的东西:
function get_all_mentions($text)
{
}
// returns an array:
1 => Jack Smith
... => ...
和
function replace_all_mentions($text)
{
}
// returns a string
text text <a href="user/1">Jack Smith</a> text text
谢谢大家!
您可以使用SimpleHTMDom:
http://simplehtmldom.sourceforge.net
<?php
include 'simplehtmldom/simple_html_dom.php';
$html = new simple_html_dom();
$html->load('text text <mention userid="1" username="Jack Smith" /> text text');
$element = $html->find("mention");
/**
* For get username attr
*/
echo '<pre>';
print_r($element[0]->attr['username']);
echo '</pre>';
#for change username
$element[0]->username = 'Hi';
# and echo Or $html->save('a.html')
echo $html;