PHP preg_match 字符串中的单词并管理每个匹配结果

PHP preg_match words inside string and manage each matching result

我需要根据每个结果(单词)管理每个匹配结果。

字符串是 SQL 句子,我需要检查字符串(SQL 句子)中以 site_ 前缀(单词)开头的所有单词(table 名称)以 site_).

开头

根据单词的不同(table名字如site_customerssite_products等),我会把单词改成另一个不同的。

示例:

我的字符串(SQL句):

SELECT * FROM site_customers LEFT JOIN site_products ....

首先.- 提取site_* 个单词(在本例中为site_customer 和site_products)。 单词并不总是由空格分隔,也由 \n\t 个字符分隔。

其次-对于这些匹配结果,以适当的方式更改它们:我需要将site_customers替换为site_customers_02,将site_products替换为new_site_products,以及我无法使用其他替换系统,因为有很多 table 和很多条件需要评估。

在这种情况下,结果应该是:

SELECT * FROM site_customers_02 LEFT JOIN new_site_products ....<br/><br/>

对于您给出的示例,您可以将 preg_replace 与模式和替换数组一起使用。请注意,我们使用 \b(单词边界)来确保我们只匹配(例如)site_products 而不是 aasite_productssite_productsxx.

$string = 'SELECT * FROM site_customers LEFT JOIN site_products';
$patterns = array(
    '/\b(site_customers)\b/',
    '/\b(site_products)\b/'
    );
$replacements = array(
    '_02',
    'new_'
    );
echo preg_replace($patterns, $replacements, $string);

输出:

SELECT * FROM site_customers_02 LEFT JOIN new_site_products

如果这些代码与您提出的问题略有不同,您应该能够根据您的需要调整此代码。

Demo on 3v4l.org

您可以将 table 的名字与 /\bsite_[a-zA-Z]*/ 匹配。如果它们包含数字,您还应该将它们与 /\bsite_[a-zA-Z0-9]*/.

匹配

然后你可以用新字符串替换它:

<?php

$string = 'SELECT * FROM site_customers LEFT JOIN site_products';

$pattern = '/\bsite_[a-zA-Z0-9]*/';

$replacement = '[=10=]_02';

echo preg_replace($pattern, $replacement, $string);

这将威胁 site_customerssite_products 一样。两者都会附加 _02.

3v4l 示例:https://3v4l.org/Ti7n4


您也可以分别威胁第一个和第二个 table,但您需要知道整个查询:

<?php

$string = 'SELECT * FROM site_customers LEFT JOIN site_products';

$pattern = '/SELECT \* FROM (\bsite_[a-zA-Z0-9]*) LEFT JOIN (\bsite_[a-zA-Z0-9]*)/';

$replacement = 'SELECT * FROM _02 LEFT JOIN new_';

echo preg_replace($pattern, $replacement, $string);

3v4l 示例:https://3v4l.org/0YorR


您还可以提取像 site_ 这样的词,然后替换它们:

<?php

$re = '/\bsite_[a-zA-Z0-9]*/';
$query = 'SELECT * FROM site_customers LEFT JOIN site_products';

preg_match_all($re, $query, $matches, PREG_SET_ORDER, 0);

// Print the entire match result
var_dump($matches);

// Replace old tables with new ones
$old = [
    $matches[0][0], // First table name
    $matches[1][0], // Second table name
];

$new = [
    $matches[0][0] . '_02', // Append _02
    'new_' . $matches[1][0], // Prepand new_
];

$query = str_replace($old, $new, $query);

// Print the new query
echo $query;

3v4l 示例:https://3v4l.org/BMpPR