【问题标题】:Transform replaced strings in array转换数组中的替换字符串
【发布时间】:2018-04-16 20:22:00
【问题描述】:

我有以下代码:

<?php
$text = 'Hey @Mathew, have u talked with @Jhon today?';
    $text = preg_replace('/(^|\s)@([A-Za-z0-9]*)/', '\1<a href="profile.php?user=\\2">@\\2</a>',$text);
?>

我的目标是通知用户被引用。 为此,我想:我将所有替换的字符串放在一个数组中,只选择名称;使用上面的例子,并按照思路,我得到了这样的结果:

['Mathew', 'Jhon']

那么,我怎样才能得到最后的结果呢?

【问题讨论】:

  • PHP 如何为您提供{'Mathew', 'Jhon'}
  • "这是数组的一个例子..." 我不知道有任何编程语言用大括号 @987654325 声明数组@,对象通常是。您是说括号[] 吗?
  • @WiktorStribiżew 这正是我所需要的。谢谢。
  • 不是一个答案,但您的模式可以改进为 @(?&lt;!\S.) 代替 (^|\s)@

标签: php arrays regex


【解决方案1】:

如果您使用preg_replace_callback,您实际上可能会在执行基于正则表达式的搜索和替换时收集匹配项:

$text = 'Hey @Mathew, have u talked with @Jhon today?';
$names = [];
$text = preg_replace_callback('/(^|\s)@([A-Za-z0-9]*)/', function($m) use (&$names) {
        $names[] = $m[2];
        return $m[1] . '<a href="profile.php?user=' . $m[2] . '">@' . $m[2] . '</a>';
    },$text);
echo "$text\n";
print_r($names);

PHP demo

输出:

Hey <a href="profile.php?user=Mathew">@Mathew</a>, have u talked with <a href="profile.php?user=Jhon">@Jhon</a> today?
Array
(
    [0] => Mathew
    [1] => Jhon
)

注意,匹配的数组变量使用use (&amp;$names) 语法传递给匿名函数。 $m 是一个匹配对象,在第一项中包含整个匹配项,并在后续项中捕获。

【讨论】:

    【解决方案2】:

    在替换文本之前,您可以使用preg_match 查找字符串中的所有用户:

    http://php.net/manual/en/function.preg-match.php

    例子:

    $text = 'Hey @Mathew, have u talked with @Jhon today?';
    
    preg_match($pattern, $text, $matches);
    var_dump($matches);
    
    $text = preg_replace('/(^|\s)@([A-Za-z0-9]*)/', '\1<a href="profile.php?user=\\2">@\\2</a>',$text);
    

    你必须改变你的模式才能让它工作。

    【讨论】:

    • 注意:未定义变量:模式
    • 您需要自己定义模式,我没有包含它,因为您的模式在 preg_match 返回的匹配数组中返回了一个空格。请尝试阅读我链接的文档,而不仅仅是复制和粘贴代码
    【解决方案3】:

    我猜你可以使用像/@[a-z0-9]+/sim 这样的正则表达式,即:

    $text = 'Hey @Mathw, have u talked with @Jhon today?';
    preg_match_all('/@[a-z0-9]+/sim', $text , $handles_array, PREG_PATTERN_ORDER);
    $text = preg_replace('/(@[a-z0-9]+)/sim', '<a href="profile.php?user=$1">$1</a>', $text);
    print($text);
    print_r($handles_array[0]);
    

    输出:

    Hey <a href="profile.php?user=@Mathw">@Mathw</a>, have u talked with <a href="profile.php?user=@Jhon">@Jhon</a> today?Array
    (
        [0] => @Mathw
        [1] => @Jhon
    )
    

    现场演示:

    https://ideone.com/oU6xbb


    注意:

    “这是一个数组的例子……”

    我不知道有什么编程语言用大括号 {} 声明数组,对象通常是这样。你的意思是括号[]

    【讨论】:

    • 看来OP替换后需要一个名字数组。
    猜你喜欢
    • 2012-04-26
    • 2010-09-28
    • 1970-01-01
    • 2013-11-08
    • 1970-01-01
    • 2014-03-21
    • 2014-12-31
    • 2010-10-31
    • 2015-10-30
    相关资源
    最近更新 更多