php regular expression to capture number from table and load into variable - php

So here is the string that im scraping a page to read (using file get contents)
<th>Kills (K)</th><td><strong>4,751</strong></td><td><strong>0</strong></td>
How can i navigate to the above section of the page contents, and then isolate the 4,751 inside the above html and load it into $kills ?
Difficulty: the number will change and have additional numbers before the comma

Ok got it to work by removing all spaces and turning the page contents into a string
<?
$url = "http://combatarms.nexon.net/Community/Profile.aspx?user=tect0n";
$raw = file_get_contents($url);
$newlines = array("\t","\n","\r","\x20\x20","\0","\x0B");
$content = str_replace($newlines, "", html_entity_decode($raw));
preg_match_all('|<th>.*?</th><td><strong>(\d+,\d+)</strong></td>|', $content,$match);
?>
This returns
Array ( [0] => Array ( [0] => Kills (K)4,751 [1] => Deaths (D)4,868 ) [1] => Array ( [0] => 4,751 [1] => 4,868 ) )

This should do it:
if (preg_match("/<th>Kills \(K\)<\/th><td><strong>([\d,]+)<\/strong>/",
$string, $matches)) {
$kills = str_replace(",","",$matches[1]);
} else {
$kills = 0;
}

This is what im using and gnarf's code returns 0
RageZ's returned an empty array
<?
$string = file_get_contents("http://combatarms.nexon.net/Community/Profile.aspx?user=tect0n");
if (preg_match("/<th>Kills \(K\)<\/th><td><strong>([\d,]+)<\/strong>/",
$string, $matches)) {
$kills = str_replace(",","",$matches[1]);
} else {
$kills = 0;
}
echo $kills;
?>
Coming up 0

here you go
preg_match_all('|<th>.*?</th><td><strong>([\d,]+)</strong></td>|x', $subject,$match);
var_dump($match);
but if I were you I would use xpath it's is safer.

preg_match_all('#\(K\).*?<strong>(.*?)</strong>#s',$html,$matches);
tell me that aint pretty

preg_match('#<table class="tbl_profile">(.*?)</table>#s',file_get_contents('http://combatarms.nexon.net/Community/Profile.aspx?user=tect0n'),$m);
preg_match_all('#<tr>.*?<t.*?>(.*?)</t.*?>.*?<t.*?>(.*?)</t.*?>.*?<t.*?>(.*?)</t.*?>.*?</tr>#s',preg_replace('#(<strong>)|(</strong>)|(<!--.*?-->)#s','',$m[1]),$r);
echo 'You got '.$r[2][1].' killz';
//print_r($r);
now tell me thaaaaaaat aint pretty, cooooool it.

Related

Add params to array request

I have a pretty large array that I would need to parse, but the request changes depending on enabled/disabled parameters.
For example:
$array['a'][1]['b'][1]['c'][1] = 'asd';
$str = $array['a'][1];
dd($str);
This would give me:
Array
(
[b] => Array
(
[1] => Array
(
[c] => Array
(
[1] => asd
)
)
)
)
Which, of course, is correct. But now, if I know, that I need also the next parameter, I would need to add that like $str = $array['a'][1]['b'];.
But since there are way too many combinations, I wondered, if I can construct the call manually, something like this":
$str = $array['a'][1];
if ($b) {
$str .= ['b'][1];
}
if ($c) {
$str .= ['c'][1];
}
dd($str);
Any hints will be appreciated.
PS: I know I can do this with eval, but was really looking for a better solution:
eval("\$str = \$array$str;");
dd($str);
It can be done with Reference
$string = "['a'][1]['b'][1]";
// Maybe, not optimal, but it's not the point of the code
preg_match_all('/\[\'?([^\]\']+)\'?\]/', $string, $steps);
// "Root" of the array
$p = &$array;
foreach($steps[1] as $s) {
// Next step with current key
if (isset($p[$s]) && is_array($p)) $p = &$p[$s];
else throw new Exception("No such item");
}
// Target value
$str = $p;
demo

Textarea lines to array using php

I have a php variable that contain value of textarea as below.
Name:Jay
Email:jayviru#demo.com
Contact:9876541230
Now I want this lines to in array as below.
Array
(
[Name] =>Jay
[Email] =>jayviru#demo.com
[Contact] =>9876541230
)
I tried below,but won't worked:-
$test=explode("<br />", $text);
print_r($test);
you can try this code using php built in PHP_EOL but there is little problem about array index so i am fixed it
<?php
$text = 'Name:Jay
Email:jayviru#demo.com
Contact:9876541230';
$array_data = explode(PHP_EOL, $text);
$final_data = array();
foreach ($array_data as $data){
$format_data = explode(':',$data);
$final_data[trim($format_data[0])] = trim($format_data[1]);
}
echo "<pre>";
print_r($final_data);
and output is :
Array
(
[Name] => Jay
[Email] => jayviru#demo.com
[Contact] => 9876541230
)
Easiest way to do :-
$textarea_array = array_map('trim',explode("\n", $textarea_value)); // to remove extra spaces from each value of array
print_r($textarea_array);
$final_array = array();
foreach($textarea_array as $textarea_arr){
$exploded_array = explode(':',$textarea_arr);
$final_array[trim($exploded_array[0])] = trim($exploded_array[1]);
}
print_r($final_array);
Output:- https://eval.in/846556
This also works for me.
$convert_to_array = explode('<br/>', $my_string);
for($i=0; $i < count($convert_to_array ); $i++)
{
$key_value = explode(':', $convert_to_array [$i]);
$end_array[$key_value [0]] = $key_value [1];
}
print_r($end_array); ?>
I think you need create 3 input:text, and parse them, because if you write down this value in text area can make a mistake, when write key. Otherwise split a string into an array, and after create new array where key will be odd value and the values will be even values old array

Replace text inside an array in PHP

I have an array in PHP $aResults full thousands of URLs that looks like this:
Array ( [0] => http://test.com/server1/Image?img=nortel.jpg )
Array ( [1] => http://test.com/server1/Image?img=network.jpg )
I need to replace the text inside each url and replace the server from server1 to server5 and the word image with photo so each url should look like this:
http://test.com/server5/photo?img=
How do i accomplish this?
I have tried a variation of str_replace functions but i cannot get this work:
$sImgURL = $aResults[1][0];
$filter_url ='server1/Image';
$replace='server5/photo';
$filtered_url = str_replace($filter_url, $replace, $aResults);
print_r($aResults);
What is the best way to accomplish this? Thanks
for ($i = 0; $i <= sizeof($aResults); $i++) {
$aResults[$i] = str_replace('server1/Image', 'server5/photo', $aResults[$i]);
}
You could use array_map and str_replace functions:
<?php
$data = array(
0 => 'http://test.com/server1/Image?img=nortel.jpg' ,
1 => 'http://test.com/server1/Image?img=network.jpg',
2 => 'http://test.com/server1/Image?img=rk.jpg',
3 => 'http://test.com/server1/Image?img=nek.jpg'
);
function foo($val){
return str_replace(
array('server1','Image'),
array('server5','photo'),
$val
);
}
$res = array_map("foo",$data);
var_dump($res);
?>
As Rizier123 suggest, you can do it in one line by:
var_dump(str_replace('server1/Image','server5/photo',$data));
Put your values to 'find' and your values to 'replace' into arrays..
$find = array('server1', 'Image');
$replace = array('server5', 'photo');
$newString = str_replace($find, $replace, $oldString);

How to replace number data within a string to a different number?

There is a string variable containing number data , say $x = "OP/99/DIR"; . The position of the number data may change at any circumstance by user desire by modifying it inside the application , and the slash bar may be changed by any other character ; but the number data is mandatory. How to replace the number data to a different number ? example OP/99/DIR is changed to OP/100/DIR.
$string="OP/99/DIR";
$replace_number=100;
$string = preg_replace('!\d+!', $replace_number, $string);
print $string;
Output:
OP/100/DIR
Assuming the number only occurs once:
$content = str_replace($originalText, $numberToReplace, $numberToReplaceWith);
To change the first occurance only:
$content = str_replace($originalText, $numberToReplace, $numberToReplaceWith, 1);
Using regex and preg_replace
$x="OP/99/DIR";
$new = 100;
$x=preg_replace('/\d+/e','$new',$x);
print $x;
The most flexible solution is to use preg_replace_callback() so you can do whatever you want with the matches. This matches a single number in the string and then replaces it for the number plus one.
root#xxx:~# more test.php
<?php
function callback($matches) {
//If there's another match, do something, if invalid
return $matches[0] + 1;
}
$d[] = "OP/9/DIR";
$d[] = "9\$OP\$DIR";
$d[] = "DIR%OP%9";
$d[] = "OP/9321/DIR";
$d[] = "9321\$OP\$DIR";
$d[] = "DIR%OP%9321";
//Change regexp to use the proper separator if needed
$d2 = preg_replace_callback("(\d+)","callback",$d);
print_r($d2);
?>
root#xxx:~# php test.php
Array
(
[0] => OP/10/DIR
[1] => 10$OP$DIR
[2] => DIR%OP%10
[3] => OP/9322/DIR
[4] => 9322$OP$DIR
[5] => DIR%OP%9322
)

Preg_replace_callback returns 2 values

I have the following code but I'm not a big fan of reg exp as they are too confusing:
<?php
$r = '|\\*(.+)\\*|';
$w = '';
$s = 'hello world *copyMe* here';
function callbk($str){
print_r($str);
foreach($str as $k=>$v) {
echo $v;
}
}
$t = preg_replace_callback($r,'callbk',$s);
//output: Array ( [0] => *copyMe* [1] => copyMe ) *copyMe*copyMe
?>
my question is why is there both "*copyMe*" and "copyMe"?
i was hoping to get either one or the other, not both.
any help would be appriciated.
Because you are using a capturing expression (). If you omit the brackets you will only get *copyMe*.

Categories