如何从字符串中提取子字符串

时间:2015-06-19 17:28:03

标签: php preg-match

所以,如果我有这个字符串

Offer ends 25 Dec 7:00pm CET -75% 27,99$ 6,99$ You're receiving

如何可靠地捕获各种数据点?即使日期/时间/百分比发生变化,它也能正常工作。

我想要它看起来基本上是:

$Percent: 75
$1: 27.99
$2. 6.99
$Ends: 25 Dec 7.00pm CET (capture everything between "Offer ends" and -**%)

任何人都可以帮助我实现这个目标吗?所有的数字/​​日期都可以改变,PM可以转向AM,CET可以转向CEST等。我不确定如何在所有可能的情况下可靠地保存它。

2 个答案:

答案 0 :(得分:0)

您可以从字符串中创建一个数组,然后使用该数组来获取所需的数据:

<?php

$string  = "Offer ends 25 Dec 7:00pm CET -75% 27,99$ 6,99$ You're receiving";

//make an array
$array = explode(" ", $string);

//to see which element of the array you need you can just print it.
echo "<pre>";
print_r($array);
echo "</pre>";

//output the data
echo "Percentage: " . $array[6]. "<br>";
echo "1: " . $array[7]. "<br>";
echo "2: " . $array[8]. "<br>";
echo "Ends: ". $array[2] . " " . $array[3] . " " . $array[4]. "<br>";
?>

答案 1 :(得分:0)

这是一个使用正则表达式和preg_match:

的快速示例
<?php

// Your data
$subject = "Offer ends 25 Dec 7:00pm CET -75% 27,99$ 6,99$ You're receiving";

// The pattern (note the use of groups in regexp with brackets)
$pattern = '/(\d{1,2} [a-z]{3} \d{1,2}:\d{2}[a-z]{2} [a-z]{3}) (\-?[0-9]{1,2}\%) (\d+,\d{2,}\$) (\d+,\d{2,}\$)/i';
$matches = [];
preg_match ( $pattern, $subject, $matches);

print_r($matches);

$Percent = $matches[2];
$price_one = $matches[3];
$price_two = $matches[4];
$Ends = $matches[1];

?>

您可以使用此网站测试/了解有关正则表达式的更多信息:https://regex101.com/