I'm trying to use regular expressions to extract a certain value from a string:
"exec_hash": "/TPPE2ChB+5HuSHs84FBgx5/EgWi0OlaEXoXq4pq3Aukhc1Ypf0mZfKCJ10w=", "events_collector": "thiiM0ahsieSiech1phithe6chahngoo8sah6aid\n"
The data I want is the hash between the quotation marks. The problem is that there are multiple quotes within the string and preg_match_all function isn't returning the correct data. I've been playing around with regex for a while but can't figure it out. Ultimately, I'd like that data to be returned into a value. Ex: $string1 = '/TPPE2ChB+5HuSHs84FBgx5/EgWi0OlaEXoXq4pq3Aukhc1Ypf0mZfKCJ10w=';
Correction: I'm using curl to grab the page content. The data isn't stored in a variable.
$matches = array();
$thing = preg_match_all('/hash": "(.*?)", "events/',$page,$matches); print_r($matches);
It spits out a long array of much more than just the hash
Can you use substr?
haven't tested this, but in theory...
$pos_of_comma = strpos($str, ",");
if($pos_of_comma !== false) {
$execHash = substr($str, 14, $pos_of_comma - 14);
}
It looks like it's json_decodable:
//Get the result from curl request:
$curlResult = '"exec_hash": "/TPPE2ChB+5HuSHs84FBgx5/EgWi0OlaEXoXq4pq3Aukhc1Ypf0mZfKCJ10w=", "events_collector": "thiiM0ahsieSiech1phithe6chahngoo8sah6aid\n"';
//Parse the result:
$parsedResult = json_decode($curlResult, true);
//Get the hash:
$hash = $parsedResult["exec_hash"];
Thank you for the suggestions.
I figured it out. I missed the escape delimiters in the expression.
preg_match_all("/exec_hash\": \"(.*?)\", /",$page,$matches);
Related
I want to trim a string and delete everything before a specific character, because I am using an API that gives me some unwanted data in its callback which I want to delete.
The Callback looks like this:
{"someVar":true,"anotherVar":false,"items":[ {"id":123456, [...] }
And I only want the code after the [ , so how can I split a string like this?
Thank you!
It is JSON, so you could just decode it:
$data = json_decode($string);
If you really want to trim up to a certain character then you can just find the character's position and then cut off everything before it:
if (($i = strpos($string, '[')) !== false) {
$string = substr($string, $i + 1);
}
You can use various functions. For example:
$someVar = explode('[',$string,2);
$wantedData = $someVar[1];
Or if you want only data between [ and ] then use:
$pattern = '~\[([^\]])\]~Ui';
if (preg_match($pattern,$inputString,$matches) {
$wantedData = $matches[1];
}
Edit:
Thats what you use if you want extract some string from another. But as #Dagon noticed, it's json and you can use other function to parse it. I will leave above anyway, because it's more general to the question of extracting string from another.
Excuse me, I am making a terrible mistake somewhere, but this is the situaton:
In php i have:
$ln = "A/RADIUS ADMITS VALUE 20";
$trg = "A/RADIUS";
$matches = array();
$zz = preg_match('#$trg\sADMITS\s(VALUE)\s([^\s]+)#',$ln,$matches);
I want to capture the word "VALUE" without quotes and the last word, here the string 20, given by ([^\s]+) . That is not a whitespace repeated more than once right?
But $zz is 0, indicating no match and $matches is empty. I also tried with
$zz = preg_match('#'.$trg.'\sADMITS\s(VALUE)\s([^\s]+)#',$ln,$matches);
same problem.
Where is the mistake I am stupidly making?
You are using single quotes to embed the $trg variable in the string, which only works when using double quotes to enclose the string. This should work:
$zz = preg_match("#$trg\sADMITS\s(VALUE)\s([^\s]+)#",$ln,$matches);
I am going to parse a log file and I wonder how I can convert such a string:
[5189192e][game]: kill killer='0:Tee' victim='1:nameless tee' weapon=5 special=0
into some kind of array:
$log['5189192e']['game']['killer'] = '0:Tee';
$log['5189192e']['game']['victim'] = '1:nameless tee';
$log['5189192e']['game']['weapon'] = '5';
$log['5189192e']['game']['special'] = '0';
The best way is to use function preg_match_all() and regular expressions.
For example to get 5189192e you need to use expression
/[0-9]{7}e/
This says that the first 7 characters are digits last character is e you can change it to fits any letter
/[0-9]{7}[a-z]+/
it is almost the same but fits every letter in the end
more advanced example with subpatterns and whole details
<?php
$matches = array();
preg_match_all('\[[0-9]{7}e\]\[game]: kill killer=\'([0-9]+):([a-zA-z]+)\' victim=\'([0-9]+):([a-zA-Z ]+)\' weapon=([0-9]+) special=([0-9])+\', $str, $matches);
print_r($matches);
?>
$str is string to be parsed
$matches contains the whole data you needed to be pared like killer id, weapon, name etc.
Using the function preg_match_all() and a regex you will be able to generate an array, which you then just have to organize into your multi-dimensional array:
here's the code:
$log_string = "[5189192e][game]: kill killer='0:Tee' victim='1:nameless tee' weapon=5 special=0";
preg_match_all("/^\[([0-9a-z]*)\]\[([a-z]*)\]: kill (.*)='(.*)' (.*)='(.*)' (.*)=([0-9]*) (.*)=([0-9]*)$/", $log_string, $result);
$log[$result[1][0]][$result[2][0]][$result[3][0]] = $result[4][0];
$log[$result[1][0]][$result[2][0]][$result[5][0]] = $result[6][0];
$log[$result[1][0]][$result[2][0]][$result[7][0]] = $result[8][0];
$log[$result[1][0]][$result[2][0]][$result[9][0]] = $result[10][0];
// $log is your formatted array
You definitely need a regex. Here is the pertaining PHP function and here is a regex syntax reference.
I've got a simple string that looks like a:104:{i:143;a:5:{s:5:"naz";s:7:"Alb";s:10:"base"}} and I'd like to save all text in quotation mark cleaning it of things like s:5 and stuff using regex. Is this possible?
Want to get everything between quotes? use: ".*" as your search string (escape " characters as required)
..also you can check out http://www.zytrax.com/tech/web/regex.htm for more help with regex. (It's got a great tool where you can test input text, RE, and see what you get out)
As long as the double quotes are matched, the following call
preg_match_all('/"([^"]*)"/',$input_string,$matches);
will give you all the text between the quotes as array of strings in $matches[1]
function session_raw_decode ($data) {
$vars = preg_split('/([a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff^|]*)\|/', $data, -1, PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE);
$result = array();
for($i = 0; isset($vars[$i]); $i++)
$result[$vars[$i++]] = unserialize($vars[$i]);
return $result;
}
I have this snippet somewhere found on my server... (no idea from where it is or if I have it written myself)
You can use it and do:
$json = json_encode(session_raw_decode($string));
This should do the job.
$var="UseCountry=1
UseCountryDefault=1
UseState=1
UseStateDefault=1
UseLocality=1
UseLocalityDefault=1
cantidad_productos=5
expireDays=5
apikey=ABQIAAAAFHktBEXrHnX108wOdzd3aBTupK1kJuoJNBHuh0laPBvYXhjzZxR0qkeXcGC_0Dxf4UMhkR7ZNb04dQ
distancia=15
AutoCoord=1
user_add_locality=0
SaveContactForm=0
ShowVoteRating=0
Listlayout=0
WidthThumbs=100
HeightThumbs=75
WidthImage=640
HeightImage=480
ShowImagesSystem=1
ShowOrderBy=0
ShowOrderByDefault=0
ShowOrderDefault=DESC
SimbolPrice=$
PositionPrice=0
FormatPrice=0
ShowLogoAgent=1
ShowReferenceInList=1
ShowCategoryInList=1
ShowTypeInList=1
ShowAddressInList=1
ShowContactLink=1
ShowMapLink=1
ShowAddShortListLink=1
ShowViewPropertiesAgentLink=1
ThumbsInAccordion=5
WidthThumbsAccordion=100
HeightThumbsAccordion=75
ShowFeaturesInList=1
ShowAllParentCategory=0
AmountPanel=
AmountForRegistered=5
RegisteredAutoPublish=1
AmountForAuthor=5
AmountForEditor=5
AmountForPublisher=5
AmountForManager=5
AmountForAdministrator=5
AutoPublish=1
MailAdminPublish=1
DetailLayout=0
ActivarTabs=0
ActivarDescripcion=1
ActivarDetails=1
ActivarVideo=1
ActivarPanoramica=1
ActivarContactar=1
ContactMailFormat=1
ActivarReservas=1
ActivarMapa=1
ShowImagesSystemDetail=1
WidthThumbsDetail=120
HeightThumbsDetail=90
idCountryDefault=1
idStateDefault=1
ms_country=1
ms_state=1
ms_locality=1
ms_category=1
ms_Subcategory=1
ms_type=1
ms_price=1
ms_bedrooms=1
ms_bathrooms=1
ms_parking=1
ShowTextSearch=1
minprice=
maxprice=
ms_catradius=1
idcatradius1=
idcatradius2=
ShowTotalResult=1
md_country=1
md_state=1
md_locality=1
md_category=1
md_type=1
showComments=0
useComment2=0
useComment3=0
useComment4=0
useComment5=0
AmountMonthsCalendar=3
StartYearCalendar=2009
StartMonthCalendar=1
PeriodOnlyWeeks=0
PeriodAmount=3
PeriodStartDay=1
apikey=ABQIAAAAJ879Hg7OSEKVrRKc2YHjixSmyv5A3ewe40XW2YiIN-ybtu7KLRQiVUIEW3WsL8vOtIeTFIVUXDOAcQ
";
in that string only i want "api==ABQIAAAAJ879Hg7OSEKVrRKc2YHjixSmyv5A3ewe40XW2YiIN-ybtu7KLRQiVUIEW3WsL8vOtIeTFIVUXDOAcQ";
plz guide me correctly;
EDIT
As shamittomar pointed out, the parse_str will not work for this situation, posted the proper regex below.
Given this seems to be a QUERY STRING, use the parse_str() function PHP provides.
UPDATE
If you want to do it with regex using preg_match() as powertieke pointed out:
preg_match('/apikey=(.*)/', $var, $matches);
echo $matches[1];
Should do the trick.
preg_match(); should be right up your alley
people are so fast to jump to preg match when this can be done with regular string functions thats faster.
$string = '
expireDays=5
apikey=ABQIAAAAFHktBEXrHnX108wOdzd3aBTupK1kJuoJNBHuh0laPBvYXhjzZxR0qkeXcGC_0Dxf4UMhkR7ZNb04dQ
distancia=15
AutoCoord=1';
//test to see what type of line break it is and explode by that.
$parts = (strstr($string,"\r\n") ? explode("\r\n",$string) : explode("\n",$string));
$data = array();
foreach($parts as $part)
{
$sub = explode("=",trim($part));
if(!empty($sub[0]) || !empty($sub[1]))
{
$data[$sub[0]] = $sub[1];
}
}
and use $data['apikey'] for your api key, i would also advise you to wrpa in function.
I can bet this is a better way to parse the string and much faster.
function ParsemyString($string)
{
$parts = (strstr($string,"\r\n") ? explode("\r\n",$string) : explode("\n",$string));
$data = array();
foreach($parts as $part)
{
$sub = explode("=",trim($part));
if(!empty($sub[0]) || !empty($sub[1]))
{
$data[$sub[0]] = $sub[1];
}
}
return $data;
}
$data = ParsemyString($string);
First of all, you are not looking for
api==ABQIAAAAJ879Hg7OSEKVrRKc2YHjixSmyv5A3ewe40XW2YiIN-ybtu7KLRQiVUIEW3WsL8vOtIeTFIVUXDOAcQ
but you are looking for
apikey=ABQIAAAAJ879Hg7OSEKVrRKc2YHjixSmyv5A3ewe40XW2YiIN-ybtu7KLRQiVUIEW3WsL8vOtIeTFIVUXDOAcQ
It is important to know if the api-key property always occurs at the end and if the length of the api-key value is always the same. I this is the case you could use the PHP substr() function which would be easiest.
If not you would most probably need a regular expression which you can feed to PHPs preg_match() function. Something along the lines of apikey==[a-zA-Z0-9\-] Which matches an api-key containing a-z in both lowercase and uppercase and also allows for dashes in the key. If you are using the preg_match() function you can retrieve the matches (and thus your api-key value).