preg_replace 具有特定数据的空值

preg_replace null with specific data

如何使用 preg_replace 将文本中的 null 个单词替换为以用户名结尾的 url?

例如:

在这个

中替换null
(1, 3, 'sam', 'sam-website', 'yes', 'null'), (2, 3, 'alex', 'alex-website', 'yes', 'null'), (3, 3, 'kabor', 'kabor-website', 'yes', 'null'),

得到这个

(1, 3, 'sam', 'sam-website', 'yes', 'http://mywebsite.com/pics.php?id=sam'), (2, 3, 'alex', 'alex-website', 'yes', 'http://mywebsite.com/pics.php?id=alex'), (3, 3, 'kabor', 'kabor-website', 'yes', 'http://mywebsite.com/pics.php?id=kabor'),

试过了,但没用

$name = preg_match('/3, \'(.*?)\',/im', $string, $matches);

$url = preg_replace_callback('/null(?=)/', function ($name){
    return ($matches[1]);
}, $string);

你的正则表达式有点不对。 im 修饰符没有任何作用,您当前的捕获机制不允许您将名称和 NULL 值分开。此外,return 没有做任何事情,$name 只会是 01$matches 是捕获的值)。

我会提取括号之间的所有值,然后使用 CSV 解析器获取每个数据点。从那里你可以重建你的字符串并 return 它。

这是一个例子:

$string = "(1, 3, 'sam', 'sam-website', 'yes', 'null'), (2, 3, 'alex', 'alex-website', 'yes', 'null'), (3, 3, 'kabor', 'kabor-website', 'yes', 'null'),";
echo preg_replace_callback('/\(([^)]+)/', function ($match) {
      $data = str_getcsv($match[1], ',', "'");
      $return = '(';
      foreach($data as $key => $element) {
           if(is_numeric($element)) {
                  $return .= $element;
           } else {
                if($key == (count($data) - 1)) {
                     $return .= "'http://mywebsite.com/pics.php?id=" . $data[2] . "'";
                } else {
                      $return .= "'" . $element . "'";
                }
            }
           $return .= ', ';
      }
      return rtrim($return, ', ');
 }, $string);

演示:https://eval.in/707446