2011-04-13 40 views
2

我输出从数据库中的一些HTML的页面,包含结构是这样的:查找文本由特定字符包裹,并使用该文本作为参数的函数

<p>Department: *|accounting|*</p> 

我想找个和替换所有用|包装的文本和|并使用中间的词作为我的翻译功能的变量。我找到了partial answer。你们可以帮我解决剩下的问题吗?谢谢。

这有点什么我正在寻找...

$html_from_database = "<p>Department: *|accounting|*</p>"; 

$updated_html = preg_replace("*|(.*?)|*", translate('accounting'),$html_from_database); 

是这样的可能吗?那么正则表达式呢?它是不是太耗费资源或贪婪?请注意,只有|之间的字符和|将是a-z A-Z -_ 0-9。

在此先感谢。

回答

1

试试这个,我只是测试它和它的作品:

preg_match_all('/\|(.*?)\|/', $source, $matches); 
foreach($matches[1] as $match) { 
    $source = str_replace($match,translate($match),$source); 
} 

$source是你的源文本。

+0

谢谢,它工作和翻译得很好。唯一的问题是$ source仍然包裹在* |中和| *。我们如何调整它? [编辑:明星符号不显示在评论显然...] – maartenmachiels 2011-04-13 18:16:06

+1

使用'foreach($ matches [1]作为$ mid => $ match)$ source = str_replace($ matches [0] [$ mid ],翻译($匹配),$源);'而不是然后。 – 2011-04-13 18:22:17

+0

谢谢,伙计!这工作。我刚刚更新了一点正则表达式,因为你的版本没有考虑到星号(由于某些原因,我不能把它放在注释中) – maartenmachiels 2011-04-13 19:41:15

1

我会在两个步骤中做到这一点,找到匹配,然后调用每个的翻译功能,并建立结果字符串。事情是这样的伪代码:

matches = preg_find(".*(\|([a-zA-Z0-9\-_]*)\|).*", sourceHtml) 
foreach match in matches 
    outputHtml += sourceHtml(section between previous match and this one) 
    outputHtml += translate(inner group from match) 
    record end position of match 
outputHtml += end of sourceHtml 
相关问题