使用 preg_replace 将整数映射到字符串

Mapping integers to string with preg_replace

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

$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'。

如有任何帮助,我们将不胜感激。

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

$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 后跟一个 space,或者如果我们匹配一个有 '5' 的字符串,或者如果我们匹配一个字符串是在字符串的末尾并且它前面有一个 space 然后它将匹配。它将匹配 '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);