php preg_match_all multiple patterns - php

[-27439367, 160818667, 'http:\/\/cs13110.vk.me\/u109515688\/video\/l_97403fde.jpg', 'Super Bass', '', '0', 38674081, 37, 0, '2:34', '3', '_8cb245a336c2e35049', '']
Hello! Here is my sample text.... I need to use preg_match for multiple patterns... I need to find:
1. -27439367
2. 165375317
3. http://cs6067.vk.me/u189929178/video/l_02613a05.jpg
4. Super Bass
5. 0
6. 38674081
7. 37
8. 2:34
9. 0
10. 3
11. _8cb245a336c2e35049
I used:
preg_match_all("/[(.*?), (.*?), '(.*?)', '(.*?)', '', '0', 0, 23, 0, '', '0', '(.*?)', '']/mis", $a, $hashtweet);

Here you go:
$json = "[-27439367, 160818667, 'http:\/\/cs13110.vk.me\/u109515688\/video\/l_97403fde.jpg', 'Super Bass', '', '0', 38674081, 37, 0, '2:34', '3', '_8cb245a336c2e35049', '']" ;
$json = preg_replace("/'/", '"', $json); //Replace single quotes by double quotes
$obj = json_decode($json);
var_dump($obj);
array (size=13)
0 => int -27439367
1 => int 160818667
2 => string 'http://cs13110.vk.me/u109515688/video/l_97403fde.jpg' (length=52)
3 => string 'Super Bass' (length=10)
4 => string '' (length=0)
5 => string '0' (length=1)
6 => int 38674081
7 => int 37
8 => int 0
9 => string '2:34' (length=4)
10 => string '3' (length=1)
11 => string '_8cb245a336c2e35049' (length=19)
12 => string '' (length=0)

Maybe strip the [] brackets and do explode(',', $input) (docs)?
Another idea: this looks like a valid JSON data, so json_decode (docs) should do the trick.

Related

How to write some string value in INI file as per the update in database

For a brief, I have a USER which has multiple INI Files uploaded to his account.
The Path and Filename are stored in the database.
So The INI file has SECTIONS then the parameter and the value.
This is my INI File sample:
[INIDetails]
SipUserName=
Password=
Domain=182.010.50.59
Proxy=5080
Port=
SipAuthName=
DisplayName=
ServerMode=Automatic
UCServer=192.168.50.5250
UCUserName=
UCPassword=
[DialPlan]
DP_Exception=
DP_Rule1=
DP_Rule2=
[Advanced]
OperationMode=1
MutePkey=16
Codec=
PTime=20
AudioMode=3
SoftwareAEC=
EchoTailLength=5
PlaybackBuffer=10
CaptureBuffer=10
JBPrefetchDelay=60
JBMaxDelay=160
SipToS=
RTPToS=00
LogLevel=
So now for values like Domain and Proxy, I store them in the database, and I let the user edit those values.
Now the problem:
If there is an update in database value, I loop through and I fetch all the files that user has and I want to update them. So I do this:
function update_ini($site_session)
{
$base_configs= $this->upload_ini_m->get_files();
//Now Here We Have Files That Has to be updated as per DATABASE PARAMS
$count = count($base_configs);
//WE KNOW THE NUMBER OF FILES TO UPDATED
for ($i=0; $i < $count; $i++)
{
$filename = $base_configs[$i]->base_ini_filename;
$path = $base_configs[$i]->file_path;
//Here We Get Final File To Process//
$file_to_update =$path.$filename;
// $file_contents = file_get_contents( $file_to_update);
//Parse the INI
$file_contents = $this->data['parameters'] = parse_ini_file($file_to_update,true);
//This is Our Array which has the values so replace the values here.
foreach ($file_contents as $key => $sections)
{
foreach ($sections as $parameter => $value)
{
//Update files here
}
}
}
}
Now I want to put the values that user inserted into database written against the parameter it has, If I update the Domain name then I just want to write the value I get from POSTand write it against the parameter.
How Can I Achieve This?
I Guess I can use STR_REPLACE but how I am not sure. I want to replace the values I get from post from the values in the File.
When I var_dump() $file_contents I Get this:
array (size=3)
'INIDetails' =>
array (size=11)
'SipUserName' => string '' (length=0)
'Password' => string '' (length=0)
'Domain' => string '182.010.50.59' (length=13)
'Proxy' => string '5080' (length=4)
'Port' => string '' (length=0)
'SipAuthName' => string '' (length=0)
'DisplayName' => string '' (length=0)
'ServerMode' => string 'Automatic' (length=9)
'UCServer' => string '192.168.50.5250' (length=15)
'UCUserName' => string '' (length=0)
'UCPassword' => string '' (length=0)
'DialPlan' =>
array (size=3)
'DP_Exception' => string '' (length=0)
'DP_Rule1' => string '' (length=0)
'DP_Rule2' => string '' (length=0)
'Advanced' =>
array (size=14)
'OperationMode' => string '1' (length=1)
'MutePkey' => string '16' (length=2)
'Codec' => string '' (length=0)
'PTime' => string '20' (length=2)
'AudioMode' => string '3' (length=1)
'SoftwareAEC' => string '' (length=0)
'EchoTailLength' => string '5' (length=1)
'PlaybackBuffer' => string '10' (length=2)
'CaptureBuffer' => string '10' (length=2)
'JBPrefetchDelay' => string '60' (length=2)
'JBMaxDelay' => string '160' (length=3)
'SipToS' => string '' (length=0)
'RTPToS' => string '00' (length=2)
'LogLevel' => string '' (length=0

My PHP code serializes, but doesn't unserialize

THis this my code .
$data = array(
'24 Jan|8:30' => '12.6',
'22 Feb|8:30' => '250',
'11 Mar|8:10' => '0',
'31 Apr|23:30' => '7',
'32 Apr|23:30' => '80',
'33 Apr|23:30' => '67',
'34 r|23:30' => '45',
'35 Ap|23:30' => '66',
'34 Lr|23:30' => '23',
'3 Apr|23:30' => '23'
);
//echo serialize($data);
$x = unserialize('a:10:{s:12:"24 Jan|8:30 ";s:4:"12.6";s:12:"22 Feb|8:30 ";s:3:"250";s:12:"11 Mar|8:10 ";s:1:"0";s:12:"31 Apr|23:30";s:1:"7";s:12:"32 Apr|23:30";s:2:"80";s:12:"33 Apr|23:30";s:2:"67";s:12:"34 r|23:30 ";s:2:"45";s:12:"35 Ap|23:30 ";s:2:"66";s:12:"34 Lr|23:30 ";s:2:"23";s:12:"3 Apr|23:30 ";s:2:"23";}');
var_dump($x);
Not work in unserialize function.
Please help!
The serialized representation of $data and the string you are trying to unserialize differ.
http://codepad.viper-7.com/3zlk1a
At offset 199 you see
s:12:"34 r|23:30 "
but the string (s) isn't 12 characters long (thats what s:12: mean). I guess something modified the serialized string directly. Just don't do it :) Always unserialize and work with the structured values.
'a:10:{s:12:"24 Jan|8:30 ";s:4:"12.6";s:12:"22 Feb|8:30 ";s:3:"250";s:12:"11 Mar|8:10 ";s:1:"0";s:12:"31 Apr|23:30";s:1:"7";s:12:"32 Apr|23:30";s:2:"80";s:12:"33 Apr|23:30";s:2:"67";s:12:"34 r|23:30 ";s:2:"45";s:12:"35 Ap|23:30 ";s:2:"66";s:12:"34 Lr|23:30 ";s:2:"23";s:12:"3 Apr|23:30 ";s:2:"23";}'
...is not a valid serialization. Specifically, the s:12:"34 r|23:30 "; segment indicates that the string 34 r|23:30 contains 12 characters, which it does not.
$a = serialize($data);
$x = unserialize($a);

accessing objects data in an array

If someone has some help/advice about how to tackle this problem I'd really appreciate it. I've created a metasearch engine that for all intensive purposes works ok, but my code is pretty breakable! The following code is a sample var_dump of the array of objects - searchEngineArray. I want to store the results of each search engine in an array, but it needs to be in some kind of generic loop that (A). won't break if one search engine doesn't return results and (B). can easily accommodate additional search engines.
object(BingSearch)[1]
private 'formatted_query' => string 'england' (length=7)
public 'search_results' =>
array
0 =>
array
'title' => string 'England - Wikipedia, the free encyclopedia' (length=42)
'url' => string 'http://en.wikipedia.org/wiki/England' (length=36)
'score' => int 30
1 =>
array
'title' => string 'BBC News - England' (length=18)
'url' => string 'http://www.bbc.co.uk/news/england/' (length=34)
'score' => int 28
2 =>
array
'title' => string 'The FA - The website for the English football association, The FA ...' (length=69)
'url' => string 'http://www.thefa.com/' (length=21)
'score' => int 26
object(BlekkoSearch)[2]
private 'formatted_query' => string 'england' (length=7)
public 'search_results' =>
array
0 =>
array
'title' => string '<strong>England</strong> - Wikipedia' (length=36)
'url' => string 'http://en.wikipedia.org/wiki/England' (length=36)
'score' => int 25
1 =>
array
'title' => string 'The official site of Visit <strong>England</strong> - The <strong>England</strong> Tourist Board' (length=96)
'url' => string 'http://www.enjoyengland.com/' (length=28)
'score' => int 23
2 =>
array
'title' => string 'Arts Council <strong>England</strong> - Arts Council' (length=52)
'url' => string 'http://www.artscouncil.org.uk/' (length=30)
'score' => int 21
object(EntirewebSearch)[3]
private 'formatted_query' => string 'england' (length=7)
public 'search_results' =>
array
0 =>
array
'title' => string 'Arts Council England | Arts Council' (length=35)
'url' => string 'http://www.artscouncil.org.uk/' (length=30)
'score' => int 20
1 =>
array
'title' => string 'Sport England ' (length=14)
'url' => string 'http://www.sportengland.org/' (length=28)
'score' => int 18
2 =>
array
'title' => string 'Bank of England ' (length=16)
'url' => string 'http://www.bankofengland.co.uk/' (length=31)
'score' => int 16
I have it working to an extent, but its just not good code really. Heres how it works at the moment, has anyone got any ideas on how to create a more generic way of storing the information?
public function storeResults($searchEnginesArray)
{
//The following is very bad
//$blekko_Array = "";
//$bing_Array = "";
//$entireweb_Array = "";
for($x=0; $x<sizeof($searchEnginesArray); $x++)
{
var_dump($searchEnginesArray[$x]);
/*switch ($searchEnginesArray[$x]->getEngineName()) {
case "Bing":
$bing_Array = $searchEnginesArray[$x]->getResults();
break;
case "Blekko":
$blekko_Array = $searchEnginesArray[$x]->getResults();
break;
case "Entireweb":
$entireweb_Array = $searchEnginesArray[$x]->getResults();
break;
default:
echo "Error: Unexpected Search Engine : ".$searchEnginesArray[$x]->getEngineName(). " Expects [Bing/Blekko/Entireweb]";
} */
}
<?
public function storeResults($searchEnginesArray) {
for($i=0;$i<count($searchEnginesArray);$i++) {
$result = $searchEnginesArray[$i]->getResults();
// Ignore engines with empty results
if( !empty($result) ) {
$results[ $searchEnginesArray[$i]->getEngineName() ] = $result;
}
}
// create an array for every engine, are you sure it's needed?
extract($results, EXTR_SKIP);
}
?>

Parsing a malformed CSV file

How can I parse a CSV like this one in PHP (there's a double quote near value 8)?
"03720108";"value 8"";"";"219";"03720108";"value";"value";"value";"";"";"";"";"";"";"value";"";"";"value";"value";
I tried with fgetscv($pointer, 4096, ';', '"');
Your data seems to be malformed starting at the prior line. You have an opening quote with no closing quote.
Yes. Notice the extra quote.
"value 8"";
You might still be able to parse this string, though:
$str = '"03720108";"value 8"";"";"219";"03720108";"value";"value";"value";"";"";"";"";"";"";"value";"";"";"value";"value";';
$parsed = array_map(
function( $str ) { return substr($str, 1, -1); },
explode(';', $str)
);
var_export($parsed);
/*
array (
0 => '03720108',
1 => 'value 8"',
2 => '',
3 => '219',
4 => '03720108',
5 => 'value',
6 => 'value',
7 => 'value',
8 => '',
9 => '',
10 => '',
11 => '',
12 => '',
13 => '',
14 => 'value',
15 => '',
16 => '',
17 => 'value',
18 => 'value',
19 => false,
)
*/
Things get a bit more complicated, though, if there are elements that contain a ; character (normally would be escaped by enclosing the value in quotes... d'oh!), and the above code assumes that you only need to parse a single line (though if you are using fgets() to read the input stream, you should be OK).

PHP Fatal error, trying to request method inside model multiple times

The error message
[23-Mar-2010 08:36:16] PHP Fatal
error: Cannot redeclare humanize()
(previously declared in
/Users/tmclssns/Sites/nadar/nadar/trunk/webapp/application/filer/models/Filer/Aggregate.php:133)
in
/Users/tmclssns/Sites/nadar/nadar/trunk/webapp/application/filer/models/Filer/Aggregate.php
on line 133
I have a "Filer" model which contains several methods to generate graphs. Each method in there related to generating graphs has the suffix "Graph" in the method name. As we have some performance issues, I try to render the graphs in advance (using cron) instead of rendering them on each request. The code below is what I came up with:
public function generategraphsAction()
{
$this->_helper->viewRenderer->setNoRender();
$config = Zend_Registry::get('config');
$id = $this->_getParam('filerid');
$filer = new Filer($id);
$filer_methods = get_class_methods($filer);
foreach ($filer_methods as $filer_method) {
if (preg_match('/^(.*)Graph$/i', $filer_method, $matches)) {
$path = $config->imaging_caching_dir . "/$id/{$matches[1]}.png";
$filer->$matches[0]($path);
}
}
// var_dump(get_class_methods($filer)); die;
}
The result from the var_dump(), when uncommented, is:
array
0 => string '__construct' (length=11)
1 => string 'find_by_name' (length=12)
2 => string 'getPartner' (length=10)
3 => string 'getSlots' (length=8)
4 => string 'getGroups' (length=9)
5 => string 'grouplist' (length=9)
6 => string 'getAggregates' (length=13)
7 => string 'getVolumes' (length=10)
8 => string 'getAggregateVolumes' (length=19)
9 => string 'getShelves' (length=10)
10 => string 'getAutoSupportHistory' (length=21)
11 => string 'getAutoSupportMail' (length=18)
12 => string 'getOrphans' (length=10)
13 => string 'getAll' (length=6)
14 => string 'getDiskRevOverview' (length=18)
15 => string 'getDiskTypeOverview' (length=19)
16 => string 'getDiskTypeSizeFunctionOverview' (length=31)
17 => string 'getLicenses' (length=11)
18 => string 'removeGroup' (length=11)
19 => string 'addGroup' (length=8)
20 => string 'hasGroup' (length=8)
21 => string 'aggdefaultGraph' (length=15)
22 => string 'aggbarGraph' (length=11)
23 => string 'voldefaultGraph' (length=15)
24 => string 'volbarGraph' (length=11)
25 => string 'replicationGraph' (length=16)
26 => string 'getReplicationData' (length=18)
27 => string 'humanize' (length=8)
28 => string 'getFiler' (length=8)
29 => string 'getOptions' (length=10)
30 => string 'getCifsInfo' (length=11)
31 => string 'getCifsStats' (length=12)
32 => string '__get' (length=5)
33 => string 'tr' (length=2)
34 => string 'trs' (length=3)
35 => string 'fieldList' (length=9)
The generategraphsAction() method finds the 'Graph' methods correctly:
array
0 => string 'aggdefaultGraph' (length=15)
1 => string 'aggdefault' (length=10)
array
0 => string 'aggbarGraph' (length=11)
1 => string 'aggbar' (length=6)
array
0 => string 'voldefaultGraph' (length=15)
1 => string 'voldefault' (length=10)
array
0 => string 'volbarGraph' (length=11)
1 => string 'volbar' (length=6)
array
0 => string 'replicationGraph' (length=16)
1 => string 'replication' (length=11)
However when the first graph is generated, it generates the above listed PHP fatal error. Anyone can come up with a solution to this? I tried to pass by reference or switch a few things around (like re declare the Filer model, $current_filer = new Filer($id); and unset() it again after the request, but resulted in the same error) without much success.
The referenced method "humanize" isn't used for anything I'm doing at the moment, but belongs to the Model because it's used in several other places. Of course, removing the method is not really an option right now, and the model contains several other methods as well so I assume if I just move the humanize method around, it will generate an error on the next one.
For reference, the humanize() method:
public function humanize ($kbytes, $unit = null) {
// KiloByte, Megabyte, GigaByte, TeraByte, PetaByte, ExaByte, ZettaByte, YottaByte
$units = array('KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB');
if (null !== $units) {
$i = array_search(substr($unit, -2), $units);
if (! $i) {
$i = floor((strlen($kbytes) - 1) / 3);
}
} else {
$i = floor((strlen($kbytes) - 1) / 3);
}
$newSize = round($kbytes / pow(1024, $i), 2);
return $newSize . $units[$i];
}
Thanks in advance for the help offered.
I expect your parenthesise are wrong and your function humanize declaration is inside a while loop hence the redeclaration.
Unless of course you are including the file that defines this function twice somewhere?
public static function sums ($aggregates) {
function humanize(&$item, $key) {
$item = Filer::humanize($item);
}
$sums = array('size_total' => 0, 'size_usable' => 0, 'size_snapshot_reserve' => 0,
'size_snapshot_used' => 0, 'size_snapshot_free' => 0,
'size_active_fs_used' => 0, 'size_active_fs_free' => 0,
'size_active_fs_reserved' => 0);
foreach ($aggregates as $aggregate) {
if ($aggregate->state !== 'online') continue;
$sums['size_total'] += $aggregate->size_total;
$sums['size_usable'] += $aggregate->size_usable;
$sums['size_snapshot_reserve'] += $aggregate->size_snapshot_reserve;
$sums['size_snapshot_used'] += $aggregate->size_snapshot_used;
$sums['size_snapshot_free'] += $aggregate->size_snapshot_free;
$sums['size_active_fs_used'] += $aggregate->size_active_fs_used;
$sums['size_active_fs_free'] += $aggregate->size_active_fs_free;
$sums['size_active_fs_reserved'] += $aggregate->size_active_fs_reserved;
}
$humanSums = $sums;
array_walk($humanSums, 'humanize');
return array($sums, $humanSums);
}
The function inside function is the culprit.
Problem fixed.
Adding if(!function_exists('humanize')) block around the method declaration solved it.

Categories