PHP: How to get specific word from string - php

This is my string: $string="VARHELLO=helloVARWELCOME=123qwa";
I want to get 'hello' and '123qwa' from string.
My pseudo code is.
if /^VARHELLO/ exist
get hello(or whatever comes after VARHELLO and before VARWELCOME)
if /^VARWELCOME/ exist
get 123qwa(or whatever comes after VARWELCOME)
Note: values from 'VARHELLO' and 'VARWELCOME' are dynamic, so 'VARHELLO' could be 'H3Ll0' or VARWELCOME could be 'W3l60m3'.
Example:
$string="VARHELLO=H3Ll0VARWELCOME=W3l60m3";

Here is some code that will parse this string out for you into a more usable array.
<?php
$string="VARHELLO=helloVARWELCOME=123qwa";
$parsed = [];
$parts = explode('VAR', $string);
foreach($parts AS $part){
if(strlen($part)){
$subParts = explode('=', $part);
$parsed[$subParts[0]] = $subParts[1];
}
}
var_dump($parsed);
Output:
array(2) {
["HELLO"]=>
string(5) "hello"
["WELCOME"]=>
string(6) "123qwa"
}
Or, an alternative using parse_str (http://php.net/manual/en/function.parse-str.php)
<?php
$string="VARHELLO=helloVARWELCOME=123qwa";
$string = str_replace('VAR', '&', $string);
var_dump($string);
parse_str($string);
var_dump($HELLO);
var_dump($WELCOME);
Output:
string(27) "&HELLO=hello&WELCOME=123qwa"
string(5) "hello"
string(6) "123qwa"

Jessica's answer is perfect, but if you want to get it using preg_match
$string="VARHELLO=helloVARWELCOME=123qwa";
preg_match('/VARHELLO=(.*?)VARWELCOME=(.*)/is', $string, $m);
var_dump($m);
your results will be $m[1] and $m[2]
array(3) {
[0]=>
string(31) "VARHELLO=helloVARWELCOME=123qwa"
[1]=>
string(5) "hello"
[2]=>
string(6) "123qwa"
}

Related

php function for rading out values from string

i want to make a php loop that puts the values from a string in 2 different variables.
I am a beginner. the numbers are always the same like "3":"6" but the length and the amount of numbers (always even). it can also be "23":"673",4:6.
You can strip characters other than numbers and delimiters, and then do explode to get an array of values.
$string = '"23":"673",4:6';
$string = preg_replace('/[^\d\:\,]/', '', $string);
$pairs = explode(',', $string);
$pairs_array = [];
foreach ($pairs as $pair) {
$pairs_array[] = explode(':', $pair);
}
var_dump($pairs_array);
This gives you:
array(2) {
[0]=>
array(2) {
[0]=>
string(2) "23"
[1]=>
string(3) "673"
}
[1]=>
array(2) {
[0]=>
string(1) "4"
[1]=>
string(1) "6"
}
}
<?php
$string = '"23":"673",4:6';
//Remove quotes from string
$string = str_replace('"','',$string);
//Split sring via comma (,)
$splited_number_list = explode(',',$string);
//Loop first list
foreach($splited_number_list as $numbers){
//Split numbers via colon
$splited_numbers = explode(':',$numbers);
//Numbers in to variable
$number1 = $splited_numbers[0];
$number2 = $splited_numbers[1];
echo $number1." - ".$number2 . "<br>";
}
?>

$matches is returning same value in preg_match_all

I have array of links, i am trying to match using preg_match_all,regex but it is giving me the same result each and every time
foreach ($result[0] as $temp) {
preg_match_all($regex1, $temp["content"], $matches);
$storeUrl[]= $matches;
}
foreach ($storeUrl as $tem) {
preg_match_all($regex2, $tem[],$matches);
$storeUrllist [$count1++]= $matches;
}
$matches is working fine for first foreach and second foreach it is always returning same output only even it is not matching
I'm just guessing that you might want to design an expression that'd be similar to:
\b(?:https?:\/\/)?(?:www\.)?\w+\.(?:org|org2|com)\b
or:
\b(?:https?:\/\/)(?:www\.)?\w+\.(?:org|org2|com)\b
or:
\b(?:https?:\/\/)(?:www\.)\w+\.(?:org|org2|com)\b
not sure though.
Test
$re = '/\b(?:https?:\/\/)?(?:www\.)?\w+\.(?:org|org2|com)\b/m';
$str = 'some content http://alice.com or https://bob.org or https://www.foo.com or or baz.org2 ';
preg_match_all($re, $str, $matches, PREG_SET_ORDER, 0);
var_dump($matches);
Output
array(4) {
[0]=>
array(1) {
[0]=>
string(16) "http://alice.com"
}
[1]=>
array(1) {
[0]=>
string(15) "https://bob.org"
}
[2]=>
array(1) {
[0]=>
string(19) "https://www.foo.com"
}
[3]=>
array(1) {
[0]=>
string(8) "baz.org2"
}
}
The expression is explained on the top right panel of regex101.com, if you wish to explore/simplify/modify it, and in this link, you can watch how it would match against some sample inputs, if you like.

preg_replace_callback, removing apostrophes

I have the following regular expression callback, and the issue that I am having, is that in the final result, the ' are removed. What can I do to prevent this from happening?
<?php
$eval = "'$server.REQUEST_URI' == '/user/photos'";
$result = preg_replace_callback('/\'(.+)\'/isU', function($matches){
$match = $matches[1];
$find = Object69::find($match);
return !empty($find) ? $find : $match;
}, $eval);
var_dump($result);
here is the result of $result
string(29) " /user/photos == /user/photos"
This is what I was expecting:
string(29) "'/user/photos' == '/user/photos'"
and here are the arrays that it finds $matches:
array(2) {
[0]=>
string(21) "'$server.REQUEST_URI'"
[1]=>
string(19) "$server.REQUEST_URI"
}
array(2) {
[0]=>
string(14) "'/user/photos'"
[1]=>
string(12) "/user/photos"
}

PHP Regular Expression to extract JSON data

I have the following string:
window['test'] = false;
window['options'] = true;
window['data'] = { "id" : 2345, "stuff": [{"id":704,"name":"test"};`
How would I go about extracting the JSON data in window['data']? The example data I provided is just a small sample of what really exists. There could be more data before and/or after window['data'].
I've tried this but had no luck:
preg_match( '#window["test"] = (.*?);\s*$#m', $html, $matches );
There are several issues that I can see.
Your string uses single quotes: window['test'] not window["test"], which you have in your regular expression. This means you should use double quotes to enclose your regular expression (or escape the quotes).
Your regular expression has unescaped brackets, which is used to create a character class. You should use \[ instead of just [.
You say you are looking for data but your regular expression looks for test.
You have a $ at the end of the regular expression, which means you won't match if there is nothing other than whitespace after the bit you matched.
Also your data seems incomplete, there are some missing brackets at the end, but I think that is just a copy-paste error.
So I would try:
php > preg_match("#window\['data'\]\s*=\s*(.*?);#", $html, $matches);
php > print_r($matches);
Array
(
[0] => window['data'] = {"id":2345,"stuff":[{"id":704,"name":"test"};
[1] => {"id":2345,"stuff":[{"id":704,"name":"test"}
)
Of course then you must use json_decode() to convert the JSON string ($matches[1]) into an object or associative array that you can use.
You can use this regex:
window\['data'\]\s*=\s*(.*?);
Working demo
The match information is:
MATCH 1
1. [67-111] `{"id":2345,"stuff":[{"id":704,"name":"test"}`
As regex101 suggests you could have a code like this:
$re = "/window\\['data'\\]\\s*=\\s*(.*);/";
$str = "window['test'] = false; window['options'] = true; window['data'] = {\"id\":2345,\"stuff\":[{\"id\":704,\"name\":\"test\"};";
preg_match_all($re, $str, $matches);
You can parse the window data with the regular expression:
/^window\[['"](\w+)['"]\]\s*=\s*(.+);\s*$/m
Then you can retrieve the pieces by their original index in the window data structures, and parse the JSON at your leisure.
$data = <<<_E_
window['test'] = false;
window['options'] = true;
window['data'] = { "id" : 2345, "stuff": [{"id":704,"name":"test"}]};
_E_;
$regex = <<<_E_
/^window\[['"](\w+)['"]\]\s*=\s*(.+);\s*$/m
_E_; // SO syntax highlighting doesnt like HEREDOCs "
if( preg_match_all($regex,$data,$matches) > 0 ) {
var_dump($matches);
$index = array_search('data',$matches[1]);
if( $index !== 0 ) {
var_dump(json_decode($matches[2][$index]));
} else { echo 'no data section'; }
} else { echo 'no matches'; }
Output:
// $matches
array(3) {
[0]=>
array(3) {
[0]=> string(24) "window['test'] = false; "
[1]=> string(26) "window['options'] = true; "
[2]=> string(69) "window['data'] = { "id" : 2345, "stuff": [{"id":704,"name":"test"}]};"
}
[1]=>
array(3) {
[0]=> string(4) "test"
[1]=> string(7) "options"
[2]=> string(4) "data"
}
[2]=>
array(3) {
[0]=> string(5) "false"
[1]=> string(4) "true"
[2]=> string(51) "{ "id" : 2345, "stuff": [{"id":704,"name":"test"}]}"
}
}
// decoded JSON
object(stdClass)#1 (2) {
["id"]=> int(2345)
["stuff"]=>
array(1) {
[0]=>
object(stdClass)#2 (2) {
["id"]=> int(704)
["name"]=> string(4) "test"
}
}
}
Note: I fixed the JSON in your example to be valid so it would actually parse.

A better way to explode twice in PHP

Given:
$val = "font-size:12px;color:#ff0000;font-family:Arial";
The following code will explode the string twice, to produce an array of arrays:
$val = explode(';',$val);
foreach($val as &$v)
$v = explode(':',$v);
var_dump($val);
The output is:
array(3) {
[0]=>
array(2) {
[0]=>
string(9) "font-size"
[1]=>
string(4) "12px"
}
[1]=>
array(2) {
[0]=>
string(4) "fill"
[1]=>
string(7) "#ff0000"
}
[2]=>
&array(2) {
[0]=>
string(11) "font-family"
[1]=>
string(5) "Arial"
}
}
Is there a more efficient / cleaner way to achieve the same result?
I'd prefer something with no lambda functions since PHP 5.2 doesn't support them. But this is a purely intellectual question anyway, so, that's just a preference.
You can try with:
$input = "font-size:12px;color:#ff0000;font-family:Arial";
preg_match_all('/([^:]*?):([^;]*);?/', $input, $matches);
$output = array_combine($matches[1], $matches[2]);
Output:
array(3) {
["font-size"]=>
string(4) "12px"
["color"]=>
string(7) "#ff0000"
["font-family"]=>
string(5) "Arial"
}
I'd recommend against references--you can run into some odd errors. But your approach is fine. Alternatively, you could do something with array_map:
$val = array_map(function($v) { return explode(':', $v); }, explode(';', $val)));

Categories