简体   繁体   English

PHP如何使用preg_match匹配字符串中的精确数字和符号?

[英]PHP How to match exact numbers and symbols in a string using preg_match?

I'm parsing some data and standardizing it for my website. 我正在解析一些数据并对我的网站进行标准化。 The data I get from parsing: 我从解析中获得的数据:

[sizes] => Array
    (
        [0] => 5
        [1] => 6
        [2] => 10
        [3] => 6+
        [4] => 7
        [5] => 7+
        [6] => 8
        [7] => 8+
        [8] => 9
    )

I need to get: 我需要得到:

[0] => US - 5
[1] => US - 6
[2] => US - 10
[3] => US - 6.5
[4] => US - 7.5
[5] => US - 8.5

I tried both preg_replace (all kind of different variations) and str_replace, but nothing seem to work. 我尝试了preg_replace(各种不同的变体)和str_replace,但似乎没有任何效果。 It seems like it overwrites values: 似乎它覆盖了值:

 $sizes[$i]= str_replace("7", "US - 7", $sizes[$i]); 
 $sizes[$i] = preg_replace('/\b6\b/', "US - 6", $sizes[$i]); 
 $sizes[$i] = preg_replace('~6\+$~m', "US - 6.5", $sizes[$i]); 
 $sizes[$i] = preg_replace('~5+$~m', "US - 5.5", $sizes[$i]);

I get back something like that: 我得到类似的东西:

        [0] => US - 10
        [1] => US - 5.US - 5
        [2] => US - 6
        [3] => US - 6.US - 5.US - 5
        [4] => US - 7
        [5] => US - 8
        [6] => US - 9
        [7] => US - US - 7.5
        [8] => US - US - 8.5

If anyone could help, I'd appreciate it. 如果有人可以提供帮助,我将不胜感激。 Thank you 谢谢

Rather than trying to use regular expressions and assuming the constant 'US - x' and the a + means .5 size, then prefix with US - and just replace the + with .5 and use array_walk() to process each element... 而不是尝试使用正则表达式并假设常量'US-x'和a +表示.5大小,然后以US - .5 ,然后将+替换为.5并使用array_walk()处理每个元素...

$size = [0 => "5",
    1 => "6",
    2 => "10",
    3 => "6+",
    4 => "7",
    5 => "7+",
    6 => "8",
    7 => "8+",
    8 => "9"];

array_walk($size, function (&$data) { 
                $data = "US - ".str_replace("+", ".5", $data); 
});
print_r($size);

outputs... 输出...

Array
(
    [0] => US - 5
    [1] => US - 6
    [2] => US - 10
    [3] => US - 6.5
    [4] => US - 7
    [5] => US - 7.5
    [6] => US - 8
    [7] => US - 8.5
    [8] => US - 9
)

You could of course use any type of loop and not just array_walk() , the main logic is the same. 当然,您可以使用任何类型的循环,而不仅仅是array_walk() ,其主要逻辑是相同的。

Here is another approach: 这是另一种方法:

<?php

$result = [];
$size = [
    0 => "5",
    1 => "6",
    2 => "10",
    3 => "6+",
    4 => "7",
    5 => "7+",
    6 => "8",
    7 => "8+",
    8 => "9"
];

foreach($size as $key => $value) {
    $result[$key] = "US - " . number_format(floatval($value), 2);
}

echo "<pre>";
print_r($result);
echo "</pre>";

Output: 输出:

Array
(
    [0] => US - 5.00
    [1] => US - 6.00
    [2] => US - 10.00
    [3] => US - 6.00
    [4] => US - 7.00
    [5] => US - 7.00
    [6] => US - 8.00
    [7] => US - 8.00
    [8] => US - 9.00
)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM