Explode with regexp - php

i have a string like {ASK(Value, Value, 'Sentence', Some_Char)} and i need to get of exploded values in (). What i am doing wrong?
preg_match_all('/\{ASK\((.*?),\)\}/', '{ASK(Value, Value, \'Sentence\', X)}', $matches);
print_r($matches);

Take out the comma from your regular expression, and it matches.
preg_match_all('/\{ASK\((.*?)\)\}/', '{ASK(Value, Value, \'Sentence\', X)}', $matches);
print_r($matches);
//Explode the matched group
$exploded = explode(',',$matches[1]);
print_r($exploded);
/*
* Note that we used $matches[1] instead of $matches[0],
* since the first element contains the entire matched
* expression, and each subsequent element contains the matching groups.
*/

$s = "{ASK(Value, Value, 'Sentence', Some_Char)}";
$p = '#\{ASK\((.*?)\)\}#';
preg_match_all($p, $s, $matches);
print_r($matches);

Simply split & explode
$Myval = "{ASK(Value, Value, 'Sentence', Some_Char)}";
$splitedVal = split('[()]', $Myval);
$explodedVal = explode(",", $splitedVal[1]);
print_r($explodedVal);
// output
Array ( [0] => Value [1] => Value [2] => 'Sentence' [3] => Some_Char )

An easy way to do this (though not entirely contained within the regex) might be:
preg_match_all('/\{ASK\([^)]*\)\}/', '{ASK(Value, Value, \'Sentence\', X)}', $matches);
$values = explode($matches[1]);

So long as your Values, Sentences, and Chars do not contain , or ), then this single regex pattern will deliver without the extra explode() call.
Pattern: ~(?:\G, |ASK\()\K[^,)]+~ (Pattern Demo)
Code: (Demo)
$string="{ASK(Value, Value, 'Sentence', Some_Char)}";
print_r(preg_match_all('~(?:\G, |ASK\()\K[^,)]+~',$string,$out)?$out[0]:[]);
Output:
Array
(
[0] => Value
[1] => Value
[2] => 'Sentence'
[3] => Some_Char
)
The "magic" is in the \G. This tells regex to continue matching at the start of the string or just after the previous match. Here is a similar answer that I've posted: https://stackoverflow.com/a/48373347/2943403

Related

How can I split a string into an array?

I try to split my string into an array. All strings between the calculation signs +/*-:
$keywords = preg_split("/[\s,-]*[+-*]+/", "quanity*price/2+tax");
This is what I try to achieve:
Array
(
[0] => quantity
[1] => price
[1] => tax
)
But the result is an empty string.
In the pattern you tried the second character class is not matching a digit and the hyphen should be escaped or placed at the beginning/end.
You could use a single character class instead. If you change the delimiter to other than / like ~ you don't have to escape the forward slash.
[-*\/+\d]+
Regex demo | Php demo
For example
$strings = [
"quanity*price/2+tax",
"quanity*price/2"
];
foreach ($strings as $string) {
$keywords = preg_split("~[-*/+\d]+~", $string, -1, PREG_SPLIT_NO_EMPTY);
print_r($keywords);
}
Output
Array
(
[0] => quanity
[1] => price
[2] => tax
)
Array
(
[0] => quanity
[1] => price
)
If you also want to match 0+ preceding whitespace chars, comma's:
[\s,]*[-*/+\d]+
Regex demo
This will split the string where any of these exist: +/* and create an array out of it:
$string = "quanity*price/2+tax";
$str_arr = preg_split ("/[-*\/+\d]+/", $string);
print_r($str_arr);
Posted code with your example for clarity.
Using the regex that The fourth bird recommended:
$keywords = preg_split("/[-*\/+\d]+/", "quanity*price/2+tax", -1, PREG_SPLIT_NO_EMPTY);
The PREG_SPLIT_NO_EMPTY should drop empty values (https://www.php.net//manual/en/function.preg-split.php).

Regular expression to extract a numeric value on a changing position within a variable string

How can I extract the bold numeric part of a string, when the most of the string can change? /data/ is always present and followed by the relevant, variable, numeric part (in this case 123456).
differentcontentLocationhttps://example.com/api/result/13548/data/123456differentstuffincludingwhitespacesandnewlines8484
$str = "differentcontentLocationhttps://example.com/api/result/13548/data/123456differentstuffincludingwhitespacesandnewlines8484";
$str2 = "differentcontentLocationhttps://example.com/api/result/13548/data/123456";
In this example I need 123456. The only constant parts in the string are /data/ and maybe the first part of the URL, like https://.
preg_match("#/data/([0-9]+)([^0-9]+)#siU", $str, $matches);
Results in Array ( [0] => /data/123456d [1] => 123456 [2] => d ), what would be acceptable. But if there's nothing following the relevant numeric part, like in $str2, this expression fails. I've tried to make the tailing part optional with preg_match("#/ads/([0-9]+)(([^0-9]+)?)#siU", $x, $matches);, but it fails, too; returning only the first number of the numeric part.
The U greediness swapping modifier makes all greedy subpattern lazy here, you should remove it together with ([^0-9]+). You also do not need DOTALL modifier because there is no . in your pattern whose behavior could be modified with that s flag.
preg_match("#/data/([0-9]+)#i", $str, $matches);
Now, the pattern will match:
/data/ - a sequence of literal chars
([0-9]+) - Group 1 capturing 1+ digits (same as (\d+))
See the PHP demo.
$str = "differentcontentLocationhttps://e...content-available-to-author-only...e.com/api/result/13548/data/123456differentstuffincludingwhitespacesandnewlines8484";
$str2 = "differentcontentLocationhttps://e...content-available-to-author-only...e.com/api/result/13548/data/123456";
preg_match("#/data/([0-9]+)#i", $str, $matches);
print_r($matches); // Array ( [0] => /data/123456 [1] => 123456 )
preg_match("#/data/([0-9]+)#i", $str2, $matches2);
print_r($matches2); // Array ( [0] => /data/123456 [1] => 123456 )

How to split a string into an array using a given regex expression

I am trying to explode / preg_split a string so that I get an array of all the values that are enclosed in ( ). I've tried the following code but I always get an empty array, I have tried many things but I cant seem to do it right
Could anyone spot what am I missing to get my desired output?
$pattern = "/^\(.*\)$/";
$string = "(y3,x3),(r4,t4)";
$output = preg_split($pattern, $string);
print_r($output);
Current output Array ( [0] => [1] => )
Desired output Array ( [0] => "(y3,x3)," [1] => "(r4,t4)" )
With preg_split() your regex should be matching the delimiters within the string to split the string into an array. Your regex is currently matching the values, and for that, you can use preg_match_all(), like so:
$pattern = "/\(.*?\)/";
$string = "(y3,x3),(r4,t4)";
preg_match_all($pattern, $string, $output);
print_r($output[0]);
This outputs:
Array
(
[0] => (y3,x3)
[1] => (r4,t4)
)
If you want to use preg_split(), you would want to match the , between ),(, but without consuming the parenthesis, like so:
$pattern = "/(?<=\)),(?=\()/";
$string = "(y3,x3),(r4,t4)";
$output = preg_split($pattern, $string);
print_r($output);
This uses a positive lookbehind and positive lookahead to find the , between the two parenthesis groups, and split on them. It also output the same as the above.
You can use a simple regex like \B,\B to split the string and improve the performance by avoiding lookahead or lookbehind regex.
\B is a non-word boundary so it will match only the , between ) and (
Here is a working example:
http://regex101.com/r/cV7bO7/1
$pattern = "/\B,\B/";
$string = "(y3,x3),(r4,t4),(r5,t5)";
$result = preg_split($pattern, $string);
$result will contain:
Array
(
[0] => (y3,x3)
[1] => (r4,t4)
[2] => (r5,t5)
)

php : regex between strings not working correctly

I need to retrieve value 6Lf4 , but its just returning array..what am i doing wrong?
<?php
$inputString = 'private="key" value="6Lf4" sent="yut"';
$matches = array();
preg_match_all('/key" value="(.*?)"/', $inputString, $matches);
echo $matches[1];
?>
Based on http://ideone.com/vDV7yE, you'll want to use $matches[1][0] to get your string:
Array
(
[0] => Array
(
[0] => key" value="6Lf4"
)
[1] => Array
(
[0] => 6Lf4
)
)
try this pattern,
(?<=(value=")).*?(?=")
See Lookahead and Lookbehind Zero-Width Assertions.
Check here: http://php.net/manual/en/function.preg-match-all.php
You'll want to do:
echo $matches[1][0];
This is because you're correct in using key 1 to get the parenthesized subpattern, but you want to get the first match of this type, so you need to get the value of THAT sub-array at index 0.
So you're halfway there, but you need to get the actual value inside the array that you're returning.

PHP: Textbox Separate Emails

If I have a textbox where a user can enter multiple emails, i.e.
test#test.com
test2#test2.com
email3#email3.com
How can I use PHP to separate each email into an array/object?
Is it possible to give the users the option to separate by ';' or ',' or a new line?
If you give the user a delimiter character, you can use explode. For instance, using ;:
$emails = explode(';', $_GET['emails']);
You could use , or \n (new line) instead of ; if you preferred.
If you wanted to divide the string based on all these characters, use preg_split:
$emails = preg_split('/[;,\n]/', $_GET['emails']);
Example:
<?php
$emails = 'test#test.com;test2#test2.com
email3#email3.com,email4#email4.com';
$emails = preg_split('/[,;\n]/', $emails);
print_r($emails);
/*
Array
(
[0] => test#test.com
[1] => test2#test2.com
[2] => email3#email3.com
[3] => email4#email4.com
)
*/
Use explode() which returns an array of strings, each of which is a substring of string formed by splitting it on boundaries formed by the string delimiter.
array explode ( string $delimiter , string $string [, int $limit ] )
Example:
<?php
$str = 'one|two|three|four';
// positive limit
print_r(explode('|', $str, 2));
// negative limit (since PHP 5.1)
print_r(explode('|', $str, -1));
?>
The above example will output:
Array
(
[0] => one
[1] => two|three|four
)
Array
(
[0] => one
[1] => two
[2] => three
)
Update:
If you want to split by an array of delimiters you would need to use preg_split() with the appropriate regular expression.
You can use a delimiter such as a space or a slash and then on the PHP side of things use the explode function php.net/explode to split it.

Categories