在标签中包装php字符串

时间:2016-12-10 11:01:16

标签: php replace extract

我从数据库中提取了这个字符串

[###TITLE###] 
 Passed in 12%. 
[###TITLE###] 
1 to 2% dearer. Maintained throughout the day. 
[###TITLE###] 
 18.5m finer 2 to 3% dearer. 19.0m coarser 1 to 2% dearer. 
[###TITLE###] 
 19.5m finer 1 to 2% dearer. 20.0m coarser firm.

我的问题是: 如何在###]和[###
之间包装文本 (我想在没有[### TITLE ###]

的文本中包含div

P.S:整篇文章只是一个字符串。

预期产出

[###TITLE###] 
 Passed in 12%. 
[###TITLE###] 
 <div class="text">1 to 2% dearer. Maintained throughout the day.</div>
[###TITLE###] 
 <div class="text">18.5m finer 2 to 3% dearer. 19.0m coarser 1 to 2% dearer.</div> 
[###TITLE###] 
 <div class="text">19.5m finer 1 to 2% dearer. 20.0m coarser firm.</div>

如何从一个变量中提取数据库[### TITLE ###] 在另一个变量中,文本的其余部分。

1 个答案:

答案 0 :(得分:0)

您可以使用基于正则表达式的字符串替换:

<?php

$input = <<< EOT
[###TITLE###]
 Passed in 12%.
[###TITLE###]
1 to 2% dearer. Maintained throughout the day.
[###TITLE###]
 18.5m finer 2 to 3% dearer. 19.0m coarser 1 to 2% dearer.
[###TITLE###]
 19.5m finer 1 to 2% dearer. 20.0m coarser firm.
EOT;

$output = preg_replace(
    '/(\])\s+([^\[]*)\s+(\[)?/m', 
    "\\1\n<div class=\"text\">\\2</div>\n\\3", 
    $input
);

var_dump($output);

这个输出是:

string(323) "[###TITLE###]
<div class="text">Passed in 12%. </div>
[###TITLE###]
<div class="text">1 to 2% dearer. Maintained throughout the day. </div>
[###TITLE###]
<div class="text">18.5m finer 2 to 3% dearer. 19.0m coarser 1 to 2% dearer. </div>
[###TITLE###]
<div class="text">19.5m finer 1 to 2% dearer. 20.0m coarser firm.</div>
"

注意:请注意输入末尾有一个尾随空格,否则表达式会输出略有不同的输出。如果有疑问,只需在输入中附加一个空白字符; - )

另一种方法,在我看来更灵活,是对所需输出的建设性创造。为此,您首先使用基于正则表达式的多行捕获。然后你可以完全按照自己的意愿制作输出:

<?php

$input = <<< EOT
[###TITLE###]
 Passed in 12%.
[###TITLE###]
1 to 2% dearer. Maintained throughout the day.
[###TITLE###]
 18.5m finer 2 to 3% dearer. 19.0m coarser 1 to 2% dearer.
[###TITLE###]
 19.5m finer 1 to 2% dearer. 20.0m coarser firm.
EOT;

preg_match_all('/(\\[.+\\]\s+)([^\[]*\s*)\s/', $input, $tokens);

$output = '';
for($i=0; $i<count($tokens[0]); $i++) {
    $output .= sprintf("%s<div class=\"text\">%s</div>\n", $tokens[1][$i], $tokens[2][$i]);
}

var_dump($output);

这里的输出是:

string(330) "[###TITLE###]
 <div class="text">Passed in 12%. </div>
[###TITLE###]
<div class="text">1 to 2% dearer. Maintained throughout the day. </div>
[###TITLE###]
 <div class="text">18.5m finer 2 to 3% dearer. 19.0m coarser 1 to 2% dearer. </div>
[###TITLE###]
 <div class="text">19.5m finer 1 to 2% dearer. 20.0m coarser firm.</div>
"

警告:在这两种情况下,必须确保的实际标题和内容行包含方括号,而不包括实际分隔标题的方括号。处理此类情况可能,但会使事情变得更加复杂。