【问题标题】:Replacing string while preserving some content [closed]在保留一些内容的同时替换字符串[关闭]
【发布时间】:2014-02-20 00:10:08
【问题描述】:

所以我想弄清楚如何输入诸如

[url=value]

把它变成

<a href="value">

当然,我想保留这个价值。感谢您的帮助!

最终我希望能够输入任何目标和替换,包括 [email=value]&lt;a href="mailto:value"&gt;

到目前为止我有:

$before = explode($fix['before'],"value");
$after = explode($fix['after'],"value");
preg_replace('/\\'.$before[0].'(.+?)'.'\\'.$before[1].'/', $after[0].'\1'.$after[1], $post);

【问题讨论】:

  • 请自行研究。 SO 不是问“如何……”问题的地方,而是“为什么……”;)
  • PHP 注意:未定义变量:$fix in /your/question on line 1

标签: php regex wildcard bbcode


【解决方案1】:

您可以使用正则表达式。在 PHP 中,您可以使用preg_replace 函数。您可以使用的示例正则表达式是/\[url=(.+)\]/,替换为&lt;a href="$1"&gt;

【讨论】:

  • 您需要将 .+ 定义为组 (.+) 或引用 $1 将不起作用
  • 是的,我已经做到了。我最终想要做的是使用包含[url=value][email=value] 等的变量并将其输入脚本并让它处理。到目前为止我有$before = explode($fix['before'],"value"); $after = explode($fix['after'],"value"); preg_replace('/\\'.$before[0].'(.+?)'.'\\'.$before[1].'/', $after[0].'\1'.$after[1], $post);
【解决方案2】:

你可以使用这个正则表达式:

\[(.*?)=([^\]]+)]

工作正则表达式示例:

http://regex101.com/r/nL6lH9

测试字符串:

[url=http://www.web.com/test.php?key=valuepair]

匹配:

match[1]: "url"
match[2]: "http://www.web.com/test.php?key=valuepair"

PHP:

$teststring = '[url=http://www.web.com/test.php?key=valuepair]';

preg_match('/\[(.*?)=([^\]]+)]/', $teststring, $match);

// So you could test if $match[1] == 'url' or 'email' or etc.

switch ($match[1]) {
    case "url":
        $output = '<a href="'.$match[2].'">Link</a>';
        break;
    case "email":
        $output = '<a href="mailto:'.$match[2].'">Send Email</a>';
        break;
}
echo str_replace($teststring, $output, $teststring);

输出:

<a href="http://www.web.com/test.php?key=valuepair">Link</a>

【讨论】:

  • 谢谢。我会看看我能走多远!
  • 不客气,祝你好运! :)
猜你喜欢
  • 1970-01-01
  • 2020-01-14
  • 1970-01-01
  • 2018-05-19
  • 1970-01-01
  • 2016-02-03
  • 2022-12-17
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多