【问题标题】:Mapping integers to string with preg_replace使用 preg_replace 将整数映射到字符串
【发布时间】:2016-01-11 06:57:44
【问题描述】:

我有一个字符串,其中包含一个或多个用空格字符分隔的整数,例如:

$string = '2 7 6 9 11';

我想用存储在数组中的相应单词替换每个数字,例如:

static $companyTypes = array('word1', 'word2', 'word3', 'word4', 'word5', 'word6', 'word7', 'word8', 'word9', 'word10', 'word11', 'word12');

所以我使用了我在此页面中找到的示例:http://php.net/manual/en/function.preg-replace.php

我定义了一个这样的模式数组:

 $pattern = array('/1/','/2/','/3/','/4/','/5/','/6/','/7/','/8/','/9/','/10/','/11/','/12/');

最后像这样使用 preg_replace 函数:

$order->company_type= preg_replace($pattern, $companyTypes, $order->company_type);

但不幸的是,此解决方案不会区分一位数字和两位数字,因此如果输入字符串是“1 11”,则输出将是“word1 word1word1”而不是“word1 word11”。

任何帮助将不胜感激。

【问题讨论】:

  • 使用单词边界\b/\b1\b//\b2\b/等等。

标签: php regex preg-replace


【解决方案1】:

完全是正则表达式的解决方案:

$pattern = array('/(^1 | 1 | 1$)/', '/(^2 | 2 | 2$)/', '/(^3 | 3 | 3$)/', '/(^4 | 4 | 4$)/', '/(^5 | 5 | 5$)/' , '/(^6 | 6 | 6$)/', '/(^7 | 7 | 7$)/',  '/(^8 | 8 | 8$)/', '/(^9 | 9 | 9$)/', '/(^10 | 10 | 10$)/', '/(^11 | 11 | 11$)/', '/(^12 | 12 | 12$)/', '/(^13 | 13 | 13$)/', '/(^14 | 14 | 14$)/');
echo preg_replace($pattern, $companyTypes, $string);

/(^5 | 5 | 5$)/ 的意思是如果一个字符串是 5 后跟一个空格,或者如果我们匹配一个带有 '5' 的字符串,或者如果我们匹配一个位于字符串末尾的字符串并且它前面有一个空格,那么它将匹配。它将匹配'5 '(字符串的开头)、' 5 '(中间的任何位置)或' 5'(字符串的末尾)。

如果其中一种公司类型与正则表达式中的某些内容匹配,您可能会遇到最初描述的问题。因此,如果您确实需要,我提供了另一种解决方案。

另一种拆分字符串的解决方案:

正则表达式可以更新为仅在完全匹配时替换。

$pattern = array('/^1$/','/^2$/','/^3$/','/^4$/','/^5$/','/^6$/','/^7$/','/^8$/','/^9$/','/^10$/','/^11$/','/^12$/','/^13$/','/^14$/');

因此,在/^10$/ 的示例中,^ 表示字符串的开头,$ 表示字符串的结尾。总而言之,这意味着如果有 10 个完全匹配。

而且,你应该真正分开你的开始,以防止任何不希望的字符串更改。因此,请使用explode 拆分您的字符串,然后遍历每个字符串部分并替换所需部分,然后将字符串与implode 重新组合在一起。

$string = '2 7 6 9 11';
$string_parts = explode(' ', $string);

$pattern = array('/^1$/','/^2$/','/^3$/','/^4$/','/^5$/','/^6$/','/^7$/','/^8$/','/^9$/','/^10$/','/^11$/','/^12$/','/^13$/','/^14$/');

$result = [];
foreach ($string_parts as $string_part) {
    $result[] = preg_replace($pattern, $companyTypes, $string_part);
}
$order->company_type = implode(' ', $result);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-08-09
    • 1970-01-01
    • 1970-01-01
    • 2017-06-21
    • 1970-01-01
    • 1970-01-01
    • 2012-01-23
    相关资源
    最近更新 更多