2015-06-19 156 views
-1

子所以,如果我有這個字符串如何提取字符串

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 -**%) 

誰能幫助我上achiving這種方式?所有的數字/​​日期可以改變,PM可以轉到AM,CET可以轉到CEST等。我不確定如何在所有可能的情況下可靠地保存它。

回答

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>"; 
?> 
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/