Extract amount with preg_match from string - php

I'm trying to extract the amounts from the follow string / text:
Offerlist: 19939 Product: Technic Time: 13.01.16 - 14:08 Delivery: txt Offer36: 0,00 EUR Offer38: 185€ Best-Offer: 0,00 Offer5: 100 Offer1: 000000 Offer34: 80,00€ Offer5443: 185€ Offer876a: 00 Best-Offer: 200
I have tried this:
if (preg_match("/(?<=Offer1:)(.*?)(?=Offer34:)/s", $output, $result)) {
$offer = trim($result[0]);
}
But the problem is, if the name or position changes, the script doesn't work anymore.

Maybe you should search for the value instead of it's siblings.
So the following script should work better:
$dates = [];
if (preg_match_all("/(\w+\d*): (\d+(,\d+)?[€]?|\d\d\.\d\d.\d\d \- \d\d:\d\d|\w+)/s", $output, $result, PREG_SET_ORDER)) {
foreach ($result as $data) {
$dates[] = [$data[1] => $data[2]];
}
}

Using preg_match_all() and very explicit programming it can be done like this:
$string = 'Offer1: 000000 Offer34: 80,00€ Offer5443: 185€ Offer876a: 00 Best-Offer: 200';
$regex = '/((best-)?offer[^:]*:)([ 0-9,€]+)/i';
preg_match_all($regex, $string, $matches);
$offers = [];
for($c = 0; $c < count($matches[1]); $c++) {
$label = substr($matches[1][$c],0,-1);
$offers[$label] = trim($matches[3][$c]);
}
var_dump($offers);
Output:
array(5) {
["Offer1"]=>
string(6) "000000"
["Offer34"]=>
string(8) "80,00€"
["Offer5443"]=>
string(6) "185€"
["Offer876a"]=>
string(2) "00"
["Best-Offer"]=>
string(3) "200"
}
Live example can be found at http://sandbox.onlinephpfunctions.com/code/549db3d4d797e5821ede99612b18ac24d19ce9e8

Related

PHP: String to multidimensional array

(Sorry for my bad English)
I have a string that I want to split into an array.
The corner brackets are multiple nested arrays.
Escaped characters should be preserved.
This is a sample string:
$string = '[[["Hello, \"how\" are you?","Good!",,,123]],,"ok"]'
The result structure should look like this:
array (
0 =>
array (
0 =>
array (
0 => 'Hello, \"how\" are you?',
1 => 'Good!',
2 => '',
3 => '',
4 => '123',
),
),
1 => '',
2 => 'ok',
)
I have tested it with:
$pattern = '/[^"\\]*(?:\\.[^"\\]*)*/s';
$return = preg_match_all($pattern, $string, null);
But this did not work properly. I do not understand these RegEx patterns (I found this in another example on this page).
I do not know whether preg_match_all is the correct command.
I hope someone can help me.
Many Thanks!!!
This is a tough one for a regex - but there is a hack answer to your question (apologies in advance).
The string is almost a valid array literal but for the ,,s. You can match those pairs and then convert to ,''s with
/,(?=,)/
Then you can eval that string into the output array you are looking for.
For example:
// input
$str1 = '[[["Hello, \\"how\\" are you?","Good!",,,123]],,"ok"]';
// replace , followed by , with ,'' with a regex
$pattern = '/,(?=,)/';
$replace = ",''";
$str2 = preg_replace($pattern, $replace, $str1);
// eval updated string
$arr = eval("return $str2;");
var_dump($arr);
I get this:
array(3) {
[0]=>
array(1) {
[0]=>
array(5) {
[0]=>
string(21) "Hello, "how" are you?"
[1]=>
string(5) "Good!"
[2]=>
string(0) ""
[3]=>
string(0) ""
[4]=>
int(123)
}
}
[1]=>
string(0) ""
[2]=>
string(2) "ok"
}
Edit
Noting the inherent dangers of eval the better option is to use json_decode with the code above e.g.:
// input
$str1 = '[[["Hello, \\"how\\" are you?","Good!",,,123]],,"ok"]';
// replace , followed by , with ,'' with a regex
$pattern = '/,(?=,)/';
$replace = ',""';
$str2 = preg_replace($pattern, $replace, $str1);
// eval updated string
$arr = json_decode($str2);
var_dump($arr);
If you can edit the code that serializes the data then it's a better idea to let the serialization be handled using json_encode & json_decode. No need to reinvent the wheel on this one.
Nice cat btw.
You might want to use a lexer in combination with a recursive function that actually builds the structure.
For your purpose, the following tokens have been used:
\[ # opening bracket
\] # closing bracket
".+?(?<!\\)" # " to ", making sure it's not escaped
,(?!,) # a comma, not followed by a comma
\d+ # at least one digit
,(?=,) # a comma followed by a comma
The rest is programming logic, see a demo on ideone.com. Inspired by this post.
class Lexer {
protected static $_terminals = array(
'~^(\[)~' => "T_OPEN",
'~^(\])~' => "T_CLOSE",
'~^(".+?(?<!\\\\)")~' => "T_ITEM",
'~^(,)(?!,)~' => "T_SEPARATOR",
'~^(\d+)~' => "T_NUMBER",
'~^(,)(?=,)~' => "T_EMPTY"
);
public static function run($line) {
$tokens = array();
$offset = 0;
while($offset < strlen($line)) {
$result = static::_match($line, $offset);
if($result === false) {
throw new Exception("Unable to parse line " . ($line+1) . ".");
}
$tokens[] = $result;
$offset += strlen($result['match']);
}
return static::_generate($tokens);
}
protected static function _match($line, $offset) {
$string = substr($line, $offset);
foreach(static::$_terminals as $pattern => $name) {
if(preg_match($pattern, $string, $matches)) {
return array(
'match' => $matches[1],
'token' => $name
);
}
}
return false;
}
// a recursive function to actually build the structure
protected static function _generate($arr=array(), $idx=0) {
$output = array();
$current = 0;
for($i=$idx;$i<count($arr);$i++) {
$type = $arr[$i]["token"];
$element = $arr[$i]["match"];
switch ($type) {
case 'T_OPEN':
list($out, $index) = static::_generate($arr, $i+1);
$output[] = $out;
$i = $index;
break;
case 'T_CLOSE':
return array($output, $i);
break;
case 'T_ITEM':
case 'T_NUMBER':
$output[] = $element;
break;
case 'T_EMPTY':
$output[] = "";
break;
}
}
return $output;
}
}
$input = '[[["Hello, \"how\" are you?","Good!",,,123]],,"ok"]';
$items = Lexer::run($input);
print_r($items);
?>

Get the difference between two strings

I am creating a wildcard search/replace function and need to find the difference between two strings. I have tried some functions like array_diff and preg_match, browsed my way trough ~10 google pages with no solution.
I have a simple solution right now, but want to implement support for unknown value before wildcard
Here's what I got:
function wildcard_search($string, $wildcard) {
$wildcards = array();
$regex = "/( |_|-|\/|-|\.|,)/";
$split_string = preg_split($regex, $string);
$split_wildcard = preg_split($regex, $wildcard);
foreach($split_wildcard as $key => $value) {
if(isset($split_string[$key]) && $split_string[$key] != $value) {
$wildcards[] = $split_string[$key];
}
}
return $wildcards;
}
Example usage:
$str1 = "I prefer Microsoft products to Apple but love Linux"; //original string
$str2 = "I prefer * products to * but love *"; //wildcard search
$value = wildcard_search($str1, $str2);
//$value should now be array([0] => "Microsoft", [1] => "Apple", [2] => "Linux");
shuffle($value);
vprintf('I prefer %s products to %s but love %s', $value);
// now we can get all kinds of outputs like:
// I prefer Microsoft products to Linux but love Apple
// I prefer Apple products to Microsoft but love Linux
// I prefer Linux products to Apple but love Microsoft
// etc..
I want to implement support for unknown value before the wildcard.
Example:
$value = wildcard_search('Stackoverflow is an awesome site', 'Stack* is an awesome site');
// $value should now be array([0] => 'overflow');
// Because the wildcard (*) represents overflow in the second string
// (We already know some parts of the string but want to find the rest)
Could this be done without to much hassle with hundreds of loops etc.?
I'd change your function to use preg_quote and replace the escaped \* character with (.*?) instead:
function wildcard_search($string, $wildcard, $caseSensitive = false) {
$regex = '/^' . str_replace('\*', '(.*?)', preg_quote($wildcard)) . '$/' . (!$caseSensitive ? 'i' : '');
if (preg_match($regex, $string, $matches)) {
return array_slice($matches, 1); //Cut away the full string (position 0)
}
return false; //We didn't find anything
}
Example:
<?php
$str1 = "I prefer Microsoft products to Apple but love Linux"; //original string
$str2 = "I prefer * products to * but love *"; //wildcard search
var_dump( wildcard_search($str1, $str2) );
$str1 = 'Stackoverflow is an awesome site';
$str2 = 'Stack* is an awesome site';
var_dump( wildcard_search($str1, $str2) );
$str1 = 'Foo';
$str2 = 'bar';
var_dump( wildcard_search($str1, $str2) );
?>
Output:
array(3) {
[0]=>
string(9) "Microsoft"
[1]=>
string(5) "Apple"
[2]=>
string(5) "Linux"
}
array(1) {
[0]=>
string(8) "overflow"
}
bool(false)
DEMO

Parsing a string separated by semicolon

How can I parse this string
name:john;phone:12345;website:www.23.com;
into becoming like this
$name = "john";
$phone = "12345"
.....
because I want to save the parameter in one table column, I see joomla using this method to save the menu/article parameter.
Something like this(explode() is the way):
$string = 'name:john;phone:12345;website:www.23.com';
$array = explode(';',$string);
foreach($array as $a){
if(!empty($a)){
$variables = explode(':',$a);
$$variables[0] = $variables[1];
}
}
echo $name;
Working example
Please note: String must be like this, variable_name:value;variable_name2:value and the variable_name or variable cant contain ; or :
Here's how I'd do it:
Use explode() and split the string with ; as the delimiter.
Loop through the result array and explode() by :
Store the second part in a variable and push it into the result array
Optionally, if you want to convert the result array back into a string, you can use implode()
Code:
$str = 'name:john;phone:12345;website:www.23.com;';
$parts = explode(';', $str);
foreach ($parts as $part) {
if(isset($part) && $part != '') {
list($item, $value) = explode(':', $part);
$result[] = $value;
}
}
Output:
Array
(
[0] => john
[1] => 12345
[2] => www.23.com
)
Now, to get these values into variables, you can simply do:
$name = $result[0];
$phone = $result[1];
$website = $result[2];
Demo!
Use explode()
explode — Split a string by string
Description
Returns an array of strings, each of which is a substring of string formed by splitting it on boundaries formed by the string delimiter.
<?php
$string = "name:john;phone:12345;website:www.23.com;";
$pieces = explode(";", $string);
var_dump($pieces);
?>
Output
array(4) {
[0]=>
string(9) "name:john"
[1]=>
string(11) "phone:12345"
[2]=>
string(18) "website:www.23.com"
[3]=>
string(0) ""
}
DEMO
try this
<?php
$str = "name:john;phone:12345;website:www.23.com";
$array=explode(";",$str);
if(count($array)!=0)
{
foreach($array as $value)
{
$data=explode(":",$value);
echo $data[0]." = ".$data[1];
echo "<br>";
}
}
?>

Regex hash and colons

I want to use regular expression to filter substrings from this string
eg: hello world #level:basic #lang:java:php #...
I am trying to produce an array with a structure like this:
Array
(
[0]=> hello world
[1]=> Array
(
[0]=> level
[1]=> basic
)
[2]=> Array
(
[0]=> lang
[1]=> java
[2]=> php
)
)
I have tried preg_match("/(.*)#(.*)[:(.*)]*/", $input_line, $output_array);
and what I have got is:
Array
(
[0] => hello world #level:basic #lang:java:php
[1] => hello world #level:basic
[2] => lang:java:php
)
In this case then I will have to apply this regex few times to the indexes and then apply a regex to filter the colon out. My question is: is it possible to create a better regex to do all in one go? what would the regex be? Thanks
You can use :
$array = explode("#", "hello world #level:basic #lang:java:php");
foreach($array as $k => &$v) {
$v = strpos($v, ":") === false ? $v : explode(":", $v);
}
print_r($array);
do this
$array = array() ;
$text = "hello world #level:basic #lang:java:php";
$array = explode("#", $text);
foreach($array as $i => $value){
$array[$i] = explode(":", trim($value));
}
print_r($array);
Got something for you:
Rules:
a tag begins with #
a tag may not contain whitespace/newline
a tag is preceeded and followed by whitespace or line beginning/ending
a tag can have several parts divided by :
Example:
#this:tag:matches this is some text #a-tag this is no tag: \#escaped
and this one tag#does:not:match
Function:
<?php
function parseTags($string)
{
static $tag_regex = '#(?<=\s|^)#([^\:\s]+)(?:\:([^\s]+))*(?=\s|$)#m';
$results = array();
preg_match_all($tag_regex, $string, $results, PREG_SET_ORDER | PREG_OFFSET_CAPTURE);
$tags = array();
foreach($results as $result) {
$tag = array(
'offset' => $result[0][1],
'raw' => $result[0][0],
'length' => strlen($result[0][0]),
0 => $result[1][0]);
if(isset($result[2]))
$tag = array_merge($tag, explode(':', $result[2][0]));
$tag['elements'] = count($tag)-3;
$tags[] = $tag;
}
return $tags;
}
?>
Result:
array(2) {
[0]=>array(7) {
["offset"]=>int(0)
["raw"]=>string(17) "#this:tag:matches"
["length"]=>int(17)
[0]=>string(4) "this"
[1]=>string(3) "tag"
[2]=>string(7) "matches"
["elements"]=>int(3)
}
[1]=>array(5) {
["offset"]=>int(36)
["raw"]=>string(6) "#a-tag"
["length"]=>int(6)
[0]=>string(5) "a-tag"
["elements"]=>int(1)
}
}
Each matched tag contains
the raw tag text
the tag offset and original length (e.g. to replace it in the string later with str... functions)
the number of elements (to safely iterate for($i = 0; $i < $tag['elements']; $i++))
This might work for you:
$results = array() ;
$text = "hello world #level:basic #lang:java:php" ;
$parts = explode("#", $text);
foreach($parts as $part){
$results[] = explode(":", $part);
}
var_dump($results);
Two ways using regex, note that you somehow need explode() since PCRE for PHP doesn't support capturing a subgroup:
$string = 'hello world #level:basic #lang:java:php';
preg_match_all('/(?<=#)[\w:]+/', $string, $m);
foreach($m[0] as $v){
$example1[] = explode(':', $v);
}
print_r($example1);
// This one needs PHP 5.3+
$example2 = array();
preg_replace_callback('/(?<=#)[\w:]+/', function($m)use(&$example2){
$example2[] = explode(':', $m[0]);
}, $string);
print_r($example2);
This give you the array structure you are looking for:
<pre><?php
$subject = 'hello world #level:basic #lang:java:php';
$array = explode('#', $subject);
foreach($array as &$value) {
$items = explode(':', trim($value));
if (sizeof($items)>1) $value = $items;
}
print_r($array);
But if you prefer you can use this abomination:
$subject = 'hello world #level:basic #lang:java:php';
$pattern = '~(?:^| ?+#)|(?:\G([^#:]+?)(?=:| #|$)|:)+~';
preg_match_all($pattern, $subject, $matches);
array_shift($matches[1]);
$lastKey = sizeof($matches[1])-1;
foreach ($matches[1] as $key=>$match) {
if (!empty($match)) $temp[]=$match;
if (empty($match) || $key==$lastKey) {
$result[] = (sizeof($temp)>1) ? $temp : $temp[0];
unset($temp);
}
}
print_r($result);

How to pull numbers from a string with curly brackets?

I have a test string which is something like this:
digit{digit}digit
I want to break this string into 3 variables. For example, 40{1}2 should be split into 40 1 2. The string could be as big as 2034{345}1245. I assume regex would be the best way to split this string.
Here's what I have so far:
$productID = preg_match('/(.*?){/', $product);
$productOptionID = preg_match('/{(.*?)}/', $product);
$optionValueID = preg_match('/}(.*?)/', $product);
No need for regular expressions here:
$str = '40{1}2';
sscanf($str, '%d{%d}%d', $part_1, $part_2, $part_3);
// $part_1 would equal: 40
// $part_2 would equal: 1
// $part_3 would equal: 2
With this method, the variables are already typecast to integers.
Try this instead:
preg_match('/^(\d+)\{(\d+)\}(\d+)$/', '123{456}789', $matches)
$productId = $matches[1];
$productOptionId = $matches[2];
$productValueId = $matches[3];
How about preg_split :
$str = '123{456}789';
$arr = preg_split("/[{}]/", $str);
print_r($arr);
output:
Array
(
[0] => 123
[1] => 456
[2] => 789
)
I would personally create a simple function that can manage the process of fetching the data from the string like so:
function processID($string)
{
$result = array();
$c = 0;
for($i = 0; $i < strlen($string); $i++)
{
if(!isset($result[$c]))
{
$result[$c] = "";
}
if($string[$i] == "{" || $string[$i] == "}")
{
$c++;
continue;
}
$result[$c] .= $string[$i];
}
return $result;
}
and then just use like:
$result = processID("2034{345}1245");
The outputted result would be like so:
array(3) {
[0]=>
string(4) "2034"
[1]=>
string(3) "345"
[2]=>
string(4) "1245"
}
and a working example can be found here: http://codepad.org/7k5tAzuy

Categories