使用str_replace或其他函数替换标记

时间:2014-03-11 02:17:16

标签: php

只有在打开和关闭时才有替换标签的方法,例如:

//search to replace
$text = '[b]this will be bold[/b] but this will be not.';
$search = array('[b]long string[/b]');
//replace with
$replace = array('<b>long string</b>');
echo str_replace($search, $replace, $text);

想要的结果:

  

这将是粗体,但这不是。

我不确定如何正确设置任何帮助都会感激不尽。

5 个答案:

答案 0 :(得分:3)

听起来你想要实现一个BBCodes系统,你需要使用正则表达式来做。

http://thesinkfiles.hubpages.com/hub/Regex-for-BBCode-in-PHP上有一篇非常好的文章解释了如何解释各种正则表达式部分的含义,以便您以后可以编写自己的附加内容。

上面转换上述示例的代码如下:

$text = '[b]this will be bold[/b] but this will be not.';
$ret = $text; // So we don't overwrite the original variable.
$ret = preg_replace('#\[b\](.+)\[\/b\]#iUs', '<b>$1</b>', $ret);

答案 1 :(得分:2)

这样的事情会做到:

//search to replace
$text = '[b]this will be bold[/b] but this will be not.';
$search = array('~\[([^]]+)\]([^][]*)\[/\1\]~');
//replace with
$replace = array('<$1>$2</$1>');
echo preg_replace($search, $replace, $text);

输出:

<b>this will be bold</b> but this will be not.

PHP demo here

正则表达式演示和解释:

\[([^]]+)\]([^][]*)\[/\1\]

Regular expression visualization

Debuggex Demo

警告:这是非常简化,并忽略了一些严重的安全问题。实际上,您必须考虑禁止<script><iframe>以及其他可能导致跨站点脚本编写注入的标记。

与往常一样,解析器可能会击败正则表达式。

如果您真的想使用正则表达式:([^]]+)替换为已列入白名单的标记组。例如:

\[(b|em|i|strong)\]([^][]*)\[/\1\]  // allows only b, em, i, and strong

答案 2 :(得分:1)

您可以使用正则表达式执行此操作:

$text = '[b]this will be bold[/b] but this will be not.';
$text = preg_replace('/\[([a-z]+)\](.*?)\[\/\1\]/', '<\1>\2</\1>', $text);

答案 3 :(得分:1)

我为您编写了高级BBcode解析功能

您可以在$tags = 'b|url';

中添加任何BBcode

例如

$tags = 'b|url|i|e|img';

还支持带有内部标记的bbcode,例如[url=http://www.website.com]blaa[/url]

这是完整的代码

function parseBBCODE($text)
{
    //bbcodes tags
    $tags = 'b|url';


    //loop tags sub tags too
    while (preg_match_all('#\[('.$tags.')=?(.*?)\](.+?)\[/\1\]#is',$text, $matches))
    foreach ($matches[0] as $key => $match)
    {
       //extract tag info
       list($tag, $param, $innertext) = array($matches[1][$key], $matches[2][$key], $matches[3][$key]);

        //match tags and replace them
        switch ($tag)
        {
          //Bold
          case 'b':
             $replacement    = '<b>'.$innertext.'</b>';
          break;
          //link url
          case 'url':
            $replacement = '<a target="_blank" href="'.($param ? $param : $innertext).'">'.$matches[3][$key].'</a>';
          break;
          default :
           $replacement = "";
        }

      $text = str_replace($match, $replacement,$text);
      unset($match,$replacement,$param);
    }

   return $text;
}


 $search = '[b]long string [/b]  [url]http://www.google.com[/url]   [url=http://www.google.com]url with tag[/url]';

 echo parseBBCODE($search);

答案 4 :(得分:-1)

echo strip_tags(“你好世界!”);