我有以下文字......
Lorem ipsum dolor坐下来,精神上的精神。 Cras lorem lacus,euismod ac convallis quis,adipiscing ut dui。
[preformatted #1]This is preformatted text I do not want to alter[/preformatted]
Ut porttitor Nunc urna dolor,porttitor vitae placerat sed,iaculis ut nibh。 Etiam dignissim,nisl[preformatted #2]This is preformatted text I do not want to alter[/preformatted]
commodo pulvinar facilisis,eros enim volutpat ante,sed feugiat risus justo vitae ipsum。 Duis lobortis hendrerit orci,non semper dolor porta sed。
我想要实现的是将所有这些预格式化的块替换为临时占位符文本,例如[placeholder1]
,[placeholder2]
,并将原始块存储在某种索引数组中,以便占位符可以在对块执行了一些外部处理之后,将其换回原件。
如果有人能指出我正确的方向,我将非常感激。提前谢谢。
答案 0 :(得分:0)
注意:我这里没有PHP,所以实际上不能尝试这个。语法可能不完美。
更清洁的回答,因为我现在更全面地了解您的用例。首先,我们接受来自用户的输入字符串,这将是一个字符串,但部分内容将采用此形式[preformatted]some text[/preformatted]
。我们想要使用preg_match_all
$input = $_POST['main_text'];
$preformatted = preg_match_all('/\[preformatted\](.*?)\[\/preformatted\]/is', $input);
现在我们按照正确的顺序在数组中预先格式化了文本字符串,我们用这样的占位符替换它们(注意 - 占位符将被编号,因为我假设您对此文本所做的任何操作可能会重新排序占位符,我们希望使用preg_replace:
以正确的顺序替换$placeholders = array();
for ($i = 1; $i <= sizeof($preformatted); $i++) {
$placeholders[$i] = '{PREFORMATTED'.$i.'}';
preg_replace('/\[preformatted\](.*?)\[\/preformatted\]/', $placeholders[$i], $input, 1);
}
(我们在for
循环中执行此操作,将每次迭代限制为一次替换,以增加占位符值。因为我们知道替换次数(sizeof($preformatted)
),所以这是一个很好的工作溶液
现在我们有一系列预先格式化的文本字符串($preformatted
),一个占位符数组($placeholders
)和一个准备好对其执行操作的文本字符串($input
)。
对文本做任何你想做的事情,然后最后用str_replace切换预先格式化的字符串:
str_replace($placeholders,$preformatted,$input);
答案 1 :(得分:0)
$blocks = array();
// gather preformatted blocks, and at the same time replace them in the
// original text with a hash
$str = preg_replace_callback('/\[preformatted #(\d+)\](.+?)\[\/preformatted\]/is',
function($match) use(&$blocks){
$hash = '<!-- ' . md5($match[2]) .' -->';
$blocks[$hash] = $match[2];
return $hash;
}, $str);
// here you do your processing on the $blocks array
// when done, put the blocks back in the text
$str = strtr($str, $blocks);
对于正确轻巧的BBcode解析器,请尝试JBBCode