I am not very professional but
I have this PHP code :
$m = mysqli_query($dblink,"select * from bot where type='movie' and ID ='$wait'");
while($a = mysqli_fetch_array($m, MYSQLI_ASSOC)){
$ex = explode(",",$a["links"]);
preg_match_all('/\b(https?|ftp|file):\/\/[-A-Z0-9+&##\/%?=~_|$!:,.;]*[A-Z0-9+&##\/%=~_|$]/i', $ex[1], $matches);
$urls = $matches[0];
foreach($urls as $url){
$s=size($url);
}
preg_match_all('/\b(https?|ftp|file):\/\/[-A-Z0-9+&##\/%?=~_|$!:,.;]*[A-Z0-9+&##\/%=~_|$]/i', $ex[1], $matches2);
$urls2 = $matches2[0];
}
and I also have http://site1.com,http://site2.com,http://site3.com in my "links" column of database.
so here is my problem : the code only shows one of the sites.
I was wondering if the problem is with foreach or explode or non of them?
thank all of you in advance!
EDIT :
so I changed my code to this :
$ex = explode(",",$a["links"]);
$url=$a["links"];
foreach($ex as $url){
$s=size($url);
...
}
and it seems to be a problem with $url because when I use a custom url for example http://test.com instead of $url it works and shows me 3 links which is the number of links in my database with the url of http://test.com.
What am I doing wrong with $url ?
$ex = explode(",",$a["links"]);
Will return an array of values (links) as follows:
$ex[0] = 'http://site1.com'
$ex[1] = 'http://site2.com'
$ex[2] = 'http://site3.com'
And you are passing only the second position of the array (index = 1 => $ex[1]) to the next line
preg_match_all('/\b(https?|ftp|file):\/\/[-A-Z0-9+&##\/%?=~_|$!:,.;]*[A-Z0-9+&##\/%=~_|$]/i', $ex[1], $matches);
so, you can do this:
foreach($ex as $url) {
preg_match_all('/\b(https?|ftp|file):\/\/[-A-Z0-9+&##\/%?=~_|$!:,.;]*[A-Z0-9+&##\/%=~_|$]/i', $url, $matches);
}
to get the matches for each url in the links database column
Related
I have a url like this
url:- url.php?gender=male&&grand=brand1&&id=$id
eg. $id may be 1, 100 ,23, 1000 any number
I am getting the url using
<?php echo $_SERVER['REQUEST_URI']; ?>
Is it possible to change the id and make the url like
url:- url.php?gender=gender&&brand=brand1&&id=$newId
where $newId can be any number except the one that is present in the url
function remove_querystring_var($url, $key) {
$url = preg_replace('/(.*)(?|&)' . $key . '=[^&]+?(&)(.*)/i', '$1$2$4', $url . '&');
$url = substr($url, 0, -2);
return $url;
}
this will do the job, pass your url and key you want to remove in this function
ex remove_querystring_var("url.php?gender=male&&grand=brand1&&id=$id","id"), it will remove id from your url
Get the id position and the remove the id using sub string.
$url = $_SERVER['REQUEST_URI'];
#Get id position and remove && by subtracting 2 from length
$pos = strrpos($url,'id') - 2;
$url = substr($url, 0, $Pos);
echo $url;
You could use $_SERVER['QUERY_STRING'] instead.
Moreover, if your 'id' value is not always at the end, getting a substr up to it wouldn't be very robust. Instead turn it into an associative array and fiddle with it.
For example, starting with /url.php?gender=male&grand=brand1&id=999&something=else
parse_str($_SERVER['QUERY_STRING'], $parsed);
unset($parsed['id']);
// there may be a better way to do this bit.
$new_args = [];
foreach($parsed as $key=>$val){
$new_args[] = "$key=$val";
}
$new_arg_str = join($new_args, '&');
$self = $_SERVER['PHP_SELF'];
$new_endpoint = "$self?$new_arg_str";
echo $new_endpoint;
result: /url.php?gender=male&grand=brand1&something=else
Bit more legible than regex as well.
Bear in mind if you're going to redirect (using header("Location: whatever") or otherwise), you'll need to be wary of redirect loops. An if statement could avoid that.
References:
http://php.net/manual/en/reserved.variables.server.php
http://php.net/manual/en/function.parse-str.php
http://php.net/manual/en/function.unset.php
http://php.net/manual/en/control-structures.foreach.php
http://php.net/manual/en/function.join.php
I have many links with parameter number - value is numbers between 1-1000
http://mysite.com?one=2&two=4&number=2
http://mysite.com?one=2&two=4&four=4&number=124
http://mysite.com?one=2&three=4&number=9
http://mysite.com?two=4&number=242
http://mysite.com?one=2&two=4&number=52
How can i remove from this parameter and value with PHP? I would like receive:
http://mysite.com?one=2&two=4
http://mysite.com?one=2&two=4&four=4
http://mysite.com?one=2&three=4
http://mysite.com?two=4
http://mysite.com?one=2&two=4
Try this:
$str = 'http://mysite.com?one=2&two=4&number=2';
$url = parse_url($str);
parse_str($url['query'], $now );
unset($now['number']);
foreach($now as $key=>$value) :
if(is_bool($value) ){
$now[$key] = ($value) ? 'true' : 'false';
}
endforeach;
$options_string=http_build_query($now);
echo $url = 'http://mysite.com?'.$options_string;
Reference : PHP function to build query string from array - not http build query
Like this
$urls = '
http://mysite.com?one=2&two=4&number=2
http://mysite.com?one=2&two=4&four=4&number=124
http://mysite.com?one=2&three=4&number=9
http://mysite.com?two=4&number=242
http://mysite.com?one=2&two=4&number=52
';
echo '<pre>';
echo preg_replace('#&number=\d+#', '', $urls);
you can build a redirection after building a new URL with $_GET['one']
Use bellow steps,this is clear aproach
1- Parse the url into an array with parse_url()
2- Extract the query portion, decompose that into an array
3- Delete the query parameters you want by unset() them from the array
4- Rebuild the original url using http_build_query()
hope this help you
You could use parse_str() which parses the string into variables. In that way you can separate them easily
I wrote example of code.
<?php
$arr = array();
$arr[] = 'http://mysite.com?one=2&two=4&number=2';
$arr[] = 'http://mysite.com?one=2&two=4&four=4&number=124';
$arr[] = 'http://mysite.com?one=2&three=4&number=9';
$arr[] = 'http://mysite.com?two=4&number=242';
$arr[] = 'http://mysite.com?one=2&two=4&number=52';
function remove_invalid_arguments(array $array_invalid, $urlString)
{
$info = array();
parse_str($urlString, $info);
foreach($array_invalid as $inv)
if(array_key_exists($inv,$info)) unset($info[$inv]);
$ret = "";
$i = 0;
foreach($info as $k=>$v)
$ret .= ($i++ ? "&" : ""). "$k=$v"; //maybe urlencode also :)
return $ret;
}
//usage
$invalid = array('number'); //array of forbidden params
foreach($arr as $k=>&$v) $v =remove_invalid_arguments($invalid, $arr[1]);
print_r($arr);
?>
Working DEMO
If "&number=" is ALWAYS after the important parameters, I'd use str_split (or explode).
The more sure way is to use parse_url(),parse_str() and http_build_query() to break the URLs down and put them back together.
As per example of your url -
$s='http://mysite.com?one=2&two=4&number=2&number2=200';
$temp =explode('&',$s);
array_pop($temp);
echo $newurl = implode("&", $last);
Output is :http://mysite.com?one=2&two=4&number=2
Have a look at this one using regex: (as an alternative, preferably use a parser)
(.+?)(?:&number=\d+)
Assuming &number=2 is the last parameter. This regex will keep the whole url except the last parameter number
Hi guys i m using this code to get the id on my url
$string = $url;
$matches = array();
preg_match_all('/.*?\/(\d+)\/?/s', $string, $matches);
$id = $matches[1][0];
this code works for urls like
http://mysite.com/page/1
http://mysite.com/page/somepage/2
http://mysite.com/page/3/?pag=1
i will have id = 1 / id = 2 / id = 3
but for a url like this
http://mysite.com/page/122-page-name/1
this returns id = 122
THe id i m try to get always will be the last part of the url or will have /?p= after
so the urls type i can have
http://mysite.com/page/1
http://mysite.com/page/some-page/2
http://mysite.com/page/12-some-name/3
http://mysite.com/page/some-page/4/?p=1
http://mysite.com/page/13-some-page/5/?p=2
id = 1 / id = 2 / id = 3 / id = 4 / id = 5
If your id will always be located at the end of your url, you could explode the contents of your url and take the last element of the resulting array. If it may include variables (like ?pag=1) you can add a validation after the explode to check for the variable.
$urlArray = explode('/', $url);
$page = end($urlArray);
if(strpos($page, 'pag')!==false){
//get the contents of the variable from the $page variable
//exploding the variable through the ? variable and getting
//the numeric characters at the end
}
I would favor URL parsing over trying to use a regex, especially if you have a wide variety of (valid) URLs to deal with.
end(array_filter(explode('/', parse_url($url, PHP_URL_PATH))));
The array_filter deals with the trailng slash.
Since it's always at the end or has ?p=x after it you can do the following:
$params = explode('/', $_SERVER['REQUEST_URI']);
$c = count($params);
if (is_int($params[$c - 1])
$id = $params[$c - 1];
else
$id = $params[$c - 2];
Not a direct answer, more of a "how to work this out for yourself" answer :]
Place this code at the top of your page, before anything else (but after <?php)
foreach($_SERVER as $k => $v) {
echo $k.' = '.$v.'<br />';
}
exit;
Now load up each of the different URIs in a different tab and look at the results. You should be able to work out what you need to do.
I need to be able to parse this sort of data in PHP:
Acct: 1
email : bleh#gmail.com
status : online
--------------------------------------------------
Acct: 2
email : dfgg#fgfg.com
status : banned
--------------------------------------------------
Acct: 3
signedupname : SomeUsername
somethingelse : offline
--------------------------------------------------
As you can see the data is largely random. The only thing that remains the same is the ----- seperating each entry and the Acct: 1 bits. The padding between each : often changes as does the variable to represent each bit of data.
I've tried going through and parsing it all myself using regex but I am defenately not skilled enough to be able to do it properly. At the end of this I want data according to the following:
Acct: <integer>
var1: <string>
var2: <string>
If that makes any sense at all. It doesn't need to be that effeciant, as I will need to do this about once a day and I do not mind waiting for how-ever long it needs.
Thank you. :)
Edit: This is what I did on my own:
<?php
$data = file_get_contents('records.txt');
$data = explode('******** Saved Host list with acct/variables ********', $data);
$data = explode('--------------------------------------------------', $data[1]);
foreach($data as &$dataz)
{
$dataz = trim($dataz);
}
$data = str_replace('Acct:', "\nAcct:", $data);
foreach($data as $dataz)
{
preg_match('/Acct: (.*)/', $dataz, $match);
$acct = $match[1];
preg_match('/: (.*)/', $dataz, $match);
$var1 = $match[1];
echo $var1;
}
?>
I got as far as extracting the Acct: part, but anything beyond that I simply can't get my head around.
This piece of code will take your entire input and produce an associative array for each record in your input:
// replace ----- with actual number of dashes
foreach (explode('-----', $input) as $entry) {
$entry = trim($entry);
$record = array();
foreach (explode("\n", $entry) as $line) {
$parts = explode(':', $line);
$varname = trim($parts[0]);
$value = trim($parts[1]);
$record[$varname] = $value;
}
// Do anything you want with $record here
}
Edit: I just had a look at the code you posted. You really don't need regular expressions for what you're trying to do. Regex can be really handy when used in the right place, but most of the time, it's not the right thing to use.
I have an array of tags that I'm pulling from a database, I am exporting the tags out into a tag cloud. I'm stuck on getting only the first instance of the word. For example:
$string = "test,test,tag,tag2,tag3";
$getTags = explode("," , $string);
foreach ($getTags as $tag ){
echo($tag);
}
This would output the test tag twice. at first i thought i could use stristr to do something like:
foreach ($getTags as $tag ){
$tag= stristr($tag , $tag);
echo($tag);
}
This is obviously silly logic and doesn't work, stristr seems to only replace the first occurrence so something like "test 123" would only get rid of the "test" and would return "123" I've seen this can also be done with regex but I haven't found a dynamic exmaple of that.
Thanks,
Brooke
Edit: unique_array() works if I'm using a static string but won't work with the data from the database because I'm using a while loop to get each rows data.
$getTag_data = mysql_query("SELECT tags FROM `news_data`");
if ($getTag_data)
{
while ($rowTags = mysql_fetch_assoc($getTag_data))
{
$getTags = array_unique(explode("," , $rowTags['tags']));
foreach ($getTags as $tag ){
echo ($tag);
}
}
}
use array_unique()
$string = "test,test,tag,tag2,tag3";
$getTags = array_unique(explode("," , $string));
foreach ($getTags as $tag ){
echo($tag);
}
Use your words as keys to the dictionary, not as values.
$allWords=array()
foreach(explode("," , $string) as $word)
$allWords[$word]=true;
//now you can extract these keys to a regular array if you want to
$allWords=array_keys($allWords);
While you are at it, you can also count them!
$wordCounters=array()
foreach(explode("," , $string) as $word)
{
if (array_key_exists($word,$wordCounters))
$wordCounters[$word]++;
else
$wordCounters=1;
}
//word list:
$wordList=array_keys($wordCounters);
//counter for some word:
echo $wordCounters['test'];
I'm assuming that each row in your table contains more than one tag, separated by coma, like this:
Row0: php, regex, stackoverflow
Row1: php, variables, scope
Row2: c#, regex
If that's the case, try this:
$getTag_data = mysql_query("SELECT tags FROM `news_data`");
//fetch all the tags you found and place it into an array (with duplicated entries)
$getTags = array();
if ($getTag_data) {
while ($row = mysql_fetch_assoc($getTag_data)) {
array_merge($getTags, explode("," , $row['tags']);
}
}
//clean up duplicity
$getTags = array_unique($getTags);
//display
foreach ($getTags as $tag ) {
echo ($tag);
}
I'd point out that this is not efficient.
Another option (already mentioned here) would be to use the tags as array keys, with the advantage of being able to count them easily.
You could do it like this:
$getTag_data = mysql_query("SELECT tags FROM `news_data`");
$getTags = array();
if ($getTag_data) {
while ($row = mysql_fetch_assoc($getTag_data)) {
$tags = explode("," , $row['tags']);
foreach($tags as $t) {
$getTags[$t] = isset($getTags[$t]) ? $getTags[$t]+1 : 1;
}
}
}
//display
foreach ($getTags as $tag => $count) {
echo "$tag ($count times)";
}
please keep in mind none of this code was tested, it's just so you get the idea.
I believe php's array_unique is what you are looking for:
http://php.net/manual/en/function.array-unique.php
Use the array_unique function before iterating over the array? It removes every duplicate string and return the unique functions.