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

时间:2018-12-17 21:11:11

标签: php regex preg-match

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

字符串是SQL语句,我需要检查字符串(SQL语句)中所有以site_开头(以site_开头的单词)的单词(表名)。

根据单词(表名,如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,但是我无法使用其他替换系统,因为有很多表和很多条件需要评估。

在这种情况下,结果应为:

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

2 个答案:

答案 0 :(得分:0)

对于您给出的示例,可以将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(
    '${1}_02',
    'new_$1'
    );
echo preg_replace($patterns, $replacements, $string);

输出:

SELECT * FROM site_customers_02 LEFT JOIN new_site_products

如果这些代码与您提出的问题略有不同,则应该能够使此代码适合您的需求。

Demo on 3v4l.org

答案 1 :(得分:0)

您可以将表名与/\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 = '$0_02';

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

这将威胁site_customerssite_products相同。两者都将附加_02

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


您还可以分别威胁第一个和第二个表,但是您需要了解整个查询:

<?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 $1_02 LEFT JOIN new_$2';

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