【问题标题】:preg_replace with urlencodepreg_replace 用 urlencode
【发布时间】:2021-06-14 16:28:34
【问题描述】:

我正在尝试使用 preg_replace 创建主题标签链接,但当主题标签中存在“”时遇到问题。我不太擅长模式,所以任何帮助都将不胜感激:

我的模式:

$hashtags_url = '/(\#)([x00-\xFF]+[a-zA-Z0-9x00-\xFF_\w]+)/';

$body = preg_replace($hashtags_url, '<a href="'.$hashtag_path.'$2" title="#$2">#$2</a>', $body);

这非常适合普通的主题标签,但问题是当我尝试对 $2 参数进行 urlencode 时。

我试过了

$hashtags_url = '/(\#)([x00-\xFF]+[a-zA-Z0-9x00-\xFF_\w]+[x00-\xFF]+[a-zA-Z0-9x00-\xFF_\w])/';

   $body = preg_replace_callback(
$hashtags_url,
function($matches) {
    return "<a href=\"$hashtag_path/hashtag/".urlencode($matches[2])."\">#".
           $matches[2]."</a>";
},
$body);

一切顺利,但现在省略了单字标签。

【问题讨论】:

  • $matches[1] 捕获#,您应该使用$matches[2]。反斜杠有什么问题?
  • 嗨!感谢您的回答!问题实际上是我的正则表达式模式。它只考虑反斜杠之前的字符,而不考虑后面的字符。我实际上正在使用matches [2]。立即编辑帖子
  • 你的$body是什么样的?并尝试$hashtags_url = '/#(\S+)/';
  • $body 示例:$body = "Text text #hashtag text text #hast/tag";

标签: php regex preg-replace preg-replace-callback


【解决方案1】:

您可以使用以下简化的正则表达式和$matches[1] 来访问用作替换参数的匿名函数中的主题标签名称:

/#(\S+)/

确保使用use 关键字将所有必要的变量传递给回调函数(请参阅use ($hashtag_path))。

PHP demo

$body = "Text text #hashtag text text #hast/tag";
$hashtag_path = '/path/to';
$hashtags_url = '/#(\S+)/';
$body = preg_replace_callback(
$hashtags_url, function($matches) use ($hashtag_path) {
    return "<a href=\"$hashtag_path/hashtag/".urlencode($matches[1])."\">".$matches[0]."</a>";
},
$body);
echo $body;

输出:

Text text <a href="/path/to/hashtag/hashtag">#hashtag</a> text text <a href="/path/to/hashtag/hast%2Ftag">#hast/tag</a>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-19
    • 2016-06-23
    • 2010-11-03
    • 2011-09-10
    • 2013-04-16
    相关资源
    最近更新 更多