My string looks like below:
Response: 311768560
311768562
311768564
I have tried:
$success_pattern="Response: ((\d+)[\n])*";
$response="Response: 311768560\n311768562\n311768564\n311768566";
preg_match("/$success_pattern/i", $response, $match);
Output:
Array (
[0] => Response: 311768560 311768562 311768564
[1] => 311768564
[2] => 311768564
)
I need an array containing all the numbers as output like:
array('311768560','311768562','311768564');
<?php
$string="Response: 311768560 311768562 311768564";
preg_match_all("/[\d]+/", $string, $matches);
print_r($matches);
Output:
Array
(
[0] => Array
(
[0] => 311768560
[1] => 311768562
[2] => 311768564
)
)
Try not to get too hung up on a specific function like preg_match(). PHP offers several ways to generate your desired output. I'll show you three different approaches:
Input:
$response = "Response: 311768560
311768562
311768564";
Method #1: explode() with substr() and strpos() (Demo)
$array = explode("\r\n", substr($response, strpos($response, ' ') + 1));
*note, this method assumes that the first string (Response ) is the only unwanted substring and that it is always first. Also, the \r may not be necessary depending on your coding environment. This is probably the fastest of my list of methods because it doesn't use regex, but it does require 3 function calls and one incrementation -- not to mention it may be too literal for your actual use case.
Method #2: preg_match_all() (Demo)
$array = preg_match_all('/\d+/', $response, $out) ? $out[0] : [];
This method is very direct, fast, and requires minimal code. If there are any drawbacks at all, they are that the preg_match_all() returns a true|false result and generates an output variable in the form of a multidimensional array. To modify this output to suit your one-dimensional requirement, I place an inline condition at the end of the function which delivers the desired data to $array.
Method #3: preg_split() (Demo)
$array = preg_split('/\D+/', $response, 0, PREG_SPLIT_NO_EMPTY);
This function behaves just like explode() except it wields the power of regex. The pattern identifies all non-digital substrings and uses them as "delimiters" and splits the string on each of them. For your input, the first delimiter is "Response: ", then the newline character(s) after: "311768560" and "311768562". The beauty of preg_split() is that it directly provides the one-dimensional array that you are seeking.
Output:
No matter which of the above methods you try, you will receive the same correct output: $array = array('311768560', '311768562', '311768564');
If any of these methods fail your actual use case, then it is probably the product of your $response string being too different from the sample data that you have posted here.
Use Array_shift() function
<?php
$str = "Response: 311768560 311768562 311768564";
$s = explode(" ",$str);
$p = array_shift($s);
print_r($s);
?>
output
Array (
[0] => 311768560
[1] => 311768562
[2] => 311768564 )
Related
I'm looking for a way to explode a string. For example, I have the following string: (we don't count the beginning - 0x)
0xa9059xbb000000000000000000000000fc7a5f48a1a1b3f48e7dcb1f23a1ea24199af4d00000000000000000000000000000000000000000000000000000000000054368
which is actually an ETH transaction input. I need to explode this string into 3 parts. Imagine 1 bunch of zeros is actually a single space and these spaces define the gates where the string should be exploded.
How can I do that?
preg_split()
This function uses a regular expression to split a string.
So in this example at two or more 0 in a row:
$arr = preg_split('/[0]{2,}/', $string);
print_r($arr);
echo PHP_EOL;
This will output the following:
Array
(
[0] => a9059xbb
[1] => fc7a5f48a1a1b3f48e7dcb1f23a1ea24199af4d
[2] => 54368
)
Be aware that you will have problems if a message itself has a 00 in it. Assuming it is used as a null-byte for "end of string", this will not happen, though.
preg_match()
This is an example using regular expressions. You can split at arbitrary points.
$string = 'a9059xbb000000000000000000000000fc7a5f48a1a1b3f48e7dcb1f23a1ea24199af4d00000000000000000000000000000000000000000000000000000000000054368';
print_r($string);
echo PHP_EOL;
$res = preg_match('/(.{4})(.{32})(.{32})/', $string, $matches);
print_r($matches);
echo PHP_EOL;
This outputs:
a9059xbb000000000000000000000000fc7a5f48a1a1b3f48e7dcb1f23a1ea24199af4d00000000000000000000000000000000000000000000000000000000000054368
Array
(
[0] => a9059xbb000000000000000000000000fc7a5f48a1a1b3f48e7dcb1f23a1ea24199a
[1] => a905
[2] => 9xbb000000000000000000000000fc7a
[3] => 5f48a1a1b3f48e7dcb1f23a1ea24199a
)
As you can see /(.{4})(.{32})(.{32})/ will find 4 bytes, then 32 and after that 32 again. Capturing groups are made with () around what you want to find. They appear in the $matches array (0 is always the whole string found).
In case you want to ignore certain parts you can express that as well:
/(.{4})9x(.{32}).{4}(.{32})/
This changes the found string:
Array
(
[0] => a9059xbb000000000000000000000000fc7a5f48a1a1b3f48e7dcb1f23a1ea24199af4d000
[1] => a905
[2] => bb000000000000000000000000fc7a5f
[3] => a1b3f48e7dcb1f23a1ea24199af4d000
)
Links
PHP documentation for the mentioned functions:
https://www.php.net/manual/en/function.preg-split.php
https://www.php.net/manual/en/book.pcre.php
Play around with the second regular expression using this demo:
https://regex101.com/r/pfZtH8/1
If you will always explode them at the same points (4 bytes(8 hexadecimal digits), 32 bytes(64 hexadecimal digits), 32 bytes(64 hexadecimal digits)), you could use substr().
$input = "0xa9059xbb000000000000000000000000fc7a5f48a1a1b3f48e7dcb1f23a1ea24199af4d00000000000000000000000000000000000000000000000000000000000054368";
$first = substr($input,2,8);
$second = substr($input,10,64);
$third = substr($input,74,64);
print_r($first);
print "<br>";
print_r($second);
print "<br>";
print_r($third);
print "<br>";
this outputs:
a9059xbb
000000000000000000000000fc7a5f48a1a1b3f48e7dcb1f23a1ea24199af4d0
0000000000000000000000000000000000000000000000000000000000054368
I have the following string url:
HostName=MyHostName;SharedAccessKeyName=SOMETHING;SharedAccessKey=VALUE+VALUE=
I need to extract the key-value pair in an array. I have used parse_str() in PHP below is my code:
<?php
$arr = array();
$str = "HostName=MyHostName&SharedAccessKeyName=SOMETHING&SharedAccessKey=VALUE+VALUE=";
parse_str($str,$arr);
var_dump($arr);
output:
array (
'HostName' => 'MyHostName',
'SharedAccessKeyName' => 'SOMETHING',
'SharedAccessKey' => 'VALUE VALUE=',
)
you can see in the SharedAccessKey char + is replaced by space for this issue, I referred the Similiar Question, Marked answer is not the correct one according to the OP scenario, This says that first do urlencode() and then pass it because parse_str() first decode URL then separate the key-values but this will return array object of a single array which return the whole string as it is like for my case its output is like:
Array
(
[HostName=MyHostName&SharedAccessKeyName=SOMETHING&SharedAccessKey=VALUE+VALUE=] =>
)
Please help me out, not for only + char rather for all the characters should come same as they by the parse_str()
You could try emulating parse_str with preg_match_all:
preg_match_all('/(?:^|\G)(\w+)=([^&]+)(?:&|$)/', $str, $matches);
print_r(array_combine($matches[1], $matches[2]));
Output:
Array (
[HostName] => MyHostName
[SharedAccessKeyName] => SOMETHING
[SharedAccessKey] => VALUE+VALUE=
)
Demo on 3v4l.org
$str = "HostName=MyHostName&SharedAccessKeyName=SOMETHING&SharedAccessKey=VALUE+VALUE=";
preg_match_all('/(?:^|G)(w+)=([^&]+)(?:&|$)/', $str, $matches);
print_r(array_combine($matches[1], $matches[2]));
I'm writing a PHP function to extract numeric ids from a string like:
$test = '123_123_Foo'
At first I took two different approaches, one with preg_match_all():
$test2 = '123_1256_Foo';
preg_match_all('/[0-9]{1,}/', $test2, $matches);
print_r($matches[0]); // Result: 'Array ( [0] => 123 [1] => 1256 )'
and other with preg_replace() and explode():
$test = preg_replace('/[^0-9_]/', '', $test);
$output = array_filter(explode('_', $test));
print_r($output); // Results: 'Array ( [0] => 123 [1] => 1256 )'
Any of them works well as long as the string does not content mixed letters and numbers like:
$test2 = '123_123_234_Foo2'
The evident result is Array ( [0] => 123 [1] => 1256 [2] => 2 )
So I wrote another regex to get rid off of mixed strings:
$test2 = preg_replace('/([a-zA-Z]{1,}[0-9]{1,}[a-zA-Z]{1,})|([0-9]{1,}[a-zA-Z]{1,}[0-9]{1,})|([a-zA-Z]{1,}[0-9]{1,})|([0-9]{1,}[a-zA-Z]{1,})|[^0-9_]/', '', $test2);
$output = array_filter(explode('_', $test2));
print_r($output); // Results: 'Array ( [0] => 123 [1] => 1256 )'
The problem is evident too, more complicated paterns like Foo2foo12foo1 would pass the filter. And here's where I got a bit stuck.
Recap:
Extract a variable ammount of chunks of numbers from string.
The string contains at least 1 number, and may contain other numbers
and letters separated by underscores.
Only numbers not preceded or followed by letters must be extracted.
Only the numbers in the first half of the string matter.
Since only the first half is needed I decided to split in the first occurrence of letter or mixed number-letter with preg_split():
$test2 = '123_123_234_1Foo2'
$output = preg_split('/([0-9]{1,}[a-zA-Z]{1,})|[^0-9_]/', $test, 2);
preg_match_all('/[0-9]{1,}/', $output[0], $matches);
print_r($matches[0]); // Results: 'Array ( [0] => 123 [1] => 123 [2] => 234 )'
The point of my question is if is there a simpler, safer or more efficient way to achieve this result.
If I understand your question correctly, you want to split an underscore-delimited string, and filter out any substrings that are not numeric. If so, this can be achieved without regex, with explode(), array_filter() and ctype_digit(); e.g:
<?php
$str = '123_123_234_1Foo2';
$digits = array_filter(explode('_', $str), function ($substr) {
return ctype_digit($substr);
});
print_r($digits);
This yields:
Array
(
[0] => 123
[1] => 123
[2] => 234
)
Note that ctype_digit():
Checks if all of the characters in the provided string are numerical.
So $digits is still an array of strings, albeit numeric.
Hope this helps :)
Getting just the numeric part of the string after the explode
$test2 = "123_123_234_1Foo2";
$digits = array_filter(explode('_', $test2 ), 'is_numeric');
var_dump($digits);
Result
array(3) { [0]=> string(3) "123" [1]=> string(3) "123" [2]=> string(3) "234" }
Use strtok
Regex isn't a magic bullet, and there are FAR simpler fixes for your problem, especially considering you're trying to split on a delimiter.
Any of the following approaches would be cleaner, and more maintainable, and the strtok() approach would probably perform better:
Use explode to create and loop through an array, checking each value.
Use preg_split to do the same, but with more a adaptable approach.
Use strtok, as it is designed exactly for this use-case.
Basic exmple for your case:
function strGetInts(string $str, str $delim) {
$word = strtok($str, $delim);
while (false !== $word) {
if (is_integer($word) {
yield (int) $word;
}
$word = strtok($delim);
}
}
$test2 = '123_1256_Foo';
foreach(strGetInts($test2, '_-') as $key {
print_r($key);
}
Note: the second argument to strtok is string containing ANY delimiter to split the string on. Thus, my example will group results into strings separated by underscores or dashes.
Additional Note: If and only if the string only needs to be split on a single delimiter (underscore only), a method using explode will likely result in better performance. For such a solution, see the other answer in this thread: https://stackoverflow.com/a/46937452/1589379 .
I get a string that looks like this
<br>
ACCEPT:YES
<br>
SMMD:tv240245ce
<br>
is contained in a variable $_session['result']
I am trying to parse through this string and get the following either in an array or as separate variables
ACCEPT:YES
tv240245ce
I first tried
to explode the string using as the delimiter, and that did not work
then I already tried
$yes = explode(":", strip_tags($_SESSION['result']));
echo print_r($yes);
which gives me an array like so
Array ( [0] => ACCEPT [1] => YESSEED [2] => tv240245ce ) 1
which gives me one of my answers.
Please what would be a great way of trying to achieve what I am trying to achieve?
is there a way to get rid of the first and last?
then use the remaining one as a delimiter to explode the string ?
or what's the best way to go about this ?
This will do it:
$data=preg_split('/\s?<br>\s?/', str_replace('SMMD:','',$data), NULL, PREG_SPLIT_NO_EMPTY);
See example here:
CodePad
You can also skip caring about the spurious <br> and treat the whole string as key:value format with a simple regex like:
preg_match_all('/^(\w+):(.*)/', $text, $result, PREG_SET_ORDER);
This requires that you really have line breaks in it though. Gives you a $result list which is easy to convert into an associative array afterwards:
[0] => Array
(
[0] => ACCEPT:YES
[1] => ACCEPT
[2] => YES
)
[1] => Array
(
[0] => SMMD:tv240245ce
[1] => SMMD
[2] => tv240245ce
)
First, do a str_replace to remove all instances of "SMMD:". Then, Explode on "< b r >\n". Sorry for weird spaced, it was encoding the line break.
Include the new line character and you should get the array you want:
$mystr = str_replace( 'SMMD:', '', $mystr );
$res_array = explode( "<br>\n", $mystr );
Right now i'm trying to get this:
Array
(
[0] => hello
[1] =>
[2] => goodbye
)
Where index 1 is the empty string.
$toBeSplit= 'hello,,goodbye';
$textSplitted = preg_split('/[,]+/', $toBeSplit, -1);
$textSplitted looks like this:
Array
(
[0] => hello
[1] => goodbye
)
I'm using PHP 5.3.2
[,]+ means one or more comma characters while as much as possible is matched. Use just /,/ and it works:
$textSplitted = preg_split('/,/', $toBeSplit, -1);
But you don’t even need regular expression:
$textSplitted = explode(',', $toBeSplit);
How about this:
$textSplitted = preg_split('/,/', $toBeSplit, -1);
Your split regex was grabbing all the commas, not just one.
Your pattern splits the text using a sequence of commas as separator (its syntax also isn't perfect, as you're using a character class for no reason), so two (or two hundred) commas count just as one.
Anyway, since your just using a literal character as separator, use explode():
$str = 'hello,,goodbye';
print_r(explode(',', $str));
output:
Array
(
[0] => hello
[1] =>
[2] => goodbye
)