Formatting url strings PHP array - php

Hi all I am sorry if this is a dumb question and I understand I might get banned for asking it but after a lot of work reading over PHP manual, reading the relevant chapters in PHP5.3 and scowering across Stackoverflow I am stuck in my tracks.
I have been universally format the url's taken in from a Search API I have tried to use parse_url(), trim and others unsuccessfully I decided upon str_replace
foreach ($jsonObj->RESULT as $value) {
$BLekko_results[] = array(
'url' => strip_tags($value->url),
'url' => str_replace("http://www.", "http://", $value->url),
'url' => str_replace("https://www.", "http://", $value->url),
'url' => str_replace( " http://", "http://", $value->url),
'url' => str_replace( " http://", "http://", $value->url),
title' => $value->url_title,); }
I plead humbly for you help ...

foreach ($jsonObj->RESULT as $value) {
$url = trim($value->url);
$find = array("http://www.", "https://www.", "https://");
$BLekko_results[] = array(
'url' => str_replace($find, "http://", $url),
'title' => $value->url_title,);
}

Perhaps try something like this:
public function processURLString($urlString) {
$urlString = trim($urlString);
if($urlString) {
$urlString = preg_replace('/https?:\/\//', '', $urlString);
$urlString = trim($urlString);
$urlString = 'http://'.$urlString;
}
return $urlString;
}
And then you can add or remove www etc...

$BLekko_results = array();
foreach ($jsonObj->RESULT as $value) {
$value = strip_tags($value->url);
$updatedURL = str_replace(array('http://www.','https://www.','https://'),"http://",$value->url);
$updatedTitle = $value->url_title;
$BLekko_results[] = array('url'=>$updatedURL,'title'=>$updatedTitle);
}
echo "<pre>";
print_r($BLekko_results);
echo "</pre>";

Related

PHP Add array and loop to code

I have a class which is working fine but I need to do multiple results.
Here is the current code:
$url = 'http://mydomain.com';
$keyword = 'somekeyword';
$RankChecker=new RankChecker(1,5);
$result=$RankChecker->find($url,$keyword);
if ($result!==false) {
echo "Your website is found at page number ".$result["page"].".";
}
What is the best way to get it to read multiple url's / keyword's ?
Put the URLs and keywords into an array and loop through it:
$urls = array(
'http://mydomain.com' => 'somekeyword',
'http://myotherdomain.com' => 'someotherkeyword'
);
$RankChecker=new RankChecker(1,5);
foreach($urls as $url => $keyword) {
$result=$RankChecker->find($url,$keyword);
if ($result!==false) {
echo "Website " . $url . " is found at page number ".$result["page"].".";
}
}
Using an array :
<?php
$websites[1] = array('url' => 'http://mydomain.com', 'keyword' => 'somekeyword');
$websites[2] = array('url' => 'http://mydomain2.com', 'keyword' => 'somekeyword2');
$websites[3] = array('url' => 'http://mydomain3.com', 'keyword' => 'somekeyword3');
// etc...
foreach ($websites as $val)
{
$RankChecker=new RankChecker(1,5);
$result=$RankChecker->find($val['url'], $val['keyword']);
if ($result!==false) {
echo "Your website is found at page number ".$result["page"].".";
}
}

What is error in my code? (php)

I write this code to replace right to left and left to right css selectors but when i run this , not replacing any text , and return source code .
<?php
$headerString = 'Content-type: text/plain; charset="utf-8"';
header($headerString);
$file = 'test.css';
$cssFile = file_get_contents($file);
$pattern1 = '/(\.|\#).*(left|right).*[\n| | |\n\n|\n ]\{/';
preg_match_all($pattern1, $cssFile, $matches);
$matches = $matches[0];
$patternT = array();
$replacementT = array();
foreach ($matches as $key1 => $val1) {
$patternT[$key1] = preg_replace(array(
'/\./',
'/\#/',
'/\:/',
'/\,/',
'/\(/',
'/\)/',
'/\//',
'/\%/',
'/\;/',
'/\{/',
'/\}/',
), array(
'\.',
'\#',
'\:',
'\,',
'\(',
'\)',
'\/',
'\%',
'\;',
'\{',
'\}',
), $val1);
}
foreach ($patternT as $key2 => $val2) {
$patternT[$key2] = '/'.$val2.'/';
}
foreach ($matches as $key3 => $val3) {
$replacementT[$key3] = preg_replace(array(
'/right/',
'/left/',
), array(
'123456789right123456789',
'123456789left123456789',
), $val3);
}
foreach ($replacementT as $key4 => $val4) {
$replacementT[$key4] = preg_replace(array(
'/123456789right123456789/',
'/123456789left123456789/',
), array(
'left',
'right',
), $val4);
}
//Work
echo preg_replace($patternT[1], $replacementT[1], $cssFile);
//Not work
echo preg_replace($patternT, $replacementT, $cssFile);
?>
So... wait, you just want to switch left and right with each other?
At its simplest, just do $out = strtr($in,array("left"=>"right","right"=>"left"));
There's a possibility this might interfere with other things - for instance, if you have leftarrow.png in a background image, it would change to rightarrow.png... maybe that's a good thing, but if it's not...
$out = preg_replace_callback("/\b(?:right|left)\b/",function($m) {
if( $m[0] == "left") return "right";
return "left";
},$in);
try using str_replcae function in this case because you know the string.
I am not a great fan of JS that is why i am suggesting this:
str_replace('/\./', '\.', $pattern1);
I hope this helps you.
Do the rest by using loop.

If array value begins with

I have an array of values.
My crawler scans the web page and inserts all the links, the links' titles and description is a multidimensional array.
But now I have a new array and I only want the links, descriptions and titles etc. if they begin with any value in the array ($bbc_values)
But I don't really know how to do this. I have have gotten pretty far in terms of the actual code but can anyone give me any ideas a) why my code isn't working b) suggestions for my problem?
$bbc_values = array('http://www.bbc.co.uk/news/health-', 'http://www.bbc.co.uk/news/politics-', 'http://www.bbc.co.uk/news/uk-', 'http://www.bbc.co.uk/news/technology-', 'http://www.bbc.co.uk/news/england-', 'http://www.bbc.co.uk/news/northern_ireland-', 'http://www.bbc.co.uk/news/scotland-', 'http://www.bbc.co.uk/news/wales-', 'http://www.bbc.co.uk/news/business-', 'http://www.bbc.co.uk/news/education-', 'http://www.bbc.co.uk/news/science_and_enviroment-', 'http://www.bbc.co.uk/news/entertainment_and_arts-', 'http://edition.cnn.com/');
foreach ($links as $link) {
$output = array(
"title" => Titles($link), //dont know what Titles is, variable or string?
"description" => getMetas($link),
"keywords" => getKeywords($link),
"link" => $link
);
if (empty($output["description"])) {
$output["description"] = getWord($link);
}
}
$data = implode( " , ", $output['link']);
foreach ($output as $new_array) {
if (in_array($output, $bbc_values)) {
$news_stories[] = $new_array;
}
var_dump($news_stories);
}
Okay, I don't completely understand the code here.
But I think $output array should be declared outside the first foreach loop and each array should be appended to it?
Because from the code you're writing, only the details of last $link will be stored inside the $output
Also, what is $data here? what are you using it for?
Turn $bbc_values into a regex:
$bbc_re = '/^('.implode('|', array_map('quotemeta', $bbc_values)).')/';
Then use this regex to filter the links.
foreach ($links as $link) {
if (preg_match($bbc_re, $link)) {
/* Do stuff with $link */
}
}
I assume you what you want is to have an array with links that starts with of the links in the bbc_values and additionally a string $data with a comma separated list of all links. Try something this :
<?php
$bbc_values = array('http://www.bbc.co.uk/news/health-', 'http://www.bbc.co.uk/news/politics-', 'http://www.bbc.co.uk/news/uk-', 'http://www.bbc.co.uk/news/technology-', 'http://www.bbc.co.uk/news/england-', 'http://www.bbc.co.uk/news/northern_ireland-', 'http://www.bbc.co.uk/news/scotland-', 'http://www.bbc.co.uk/news/wales-', 'http://www.bbc.co.uk/news/business-', 'http://www.bbc.co.uk/news/education-', 'http://www.bbc.co.uk/news/science_and_enviroment-', 'http://www.bbc.co.uk/news/entertainment_and_arts-', 'http://edition.cnn.com/');
$news_stories = array();
$all_links = array();
$news_links = array();
foreach ($links as $link) {
$item = array(
"title" => Titles($link),
"description" => getMetas($link),
"keywords" => getKeywords($link),
"link" => $link
);
if (empty($item["description"])) {
$item["description"] = getWord($link);
}
foreach($bbc_values as $bbc_value) {
// note the '===' . this is important
if(strpos($item['link'], $bbc_value) === 0) {
$news_stories []= $item;
$news_links []=$item['link'];
break;
}
}
$all_links[] = $item['link'];
}
$data_all_links = implode(' , ', $all_links);
$data_news_links = implode(' , ', $news_links);
var_dump($news_stories);

Extracting and grouping database data to an array

I have a database field called "servers"
This field has a link in each row, this field content:
> http://www.rapidshare.com/download1
> http://www.rapidshare.com/download2
> http://www.rapidshare.com/download3
> http://www.megaupload.com/download1
> http://www.megaupload.com/download2
> http://www.megaupload.com/download3
> http://www.fileserve.com/download1
> http://www.fileserve.com/download2
> http://www.fileserve.com/download3
I want to create an array with all the server names, and create more array with links inside.
That's how it should be:
$servers = array(
'rapidshare' => array(
'link1' => 'http://www.rapidshare.com/download1',
'link2' => 'http://www.rapidshare.com/download2',
'link3' => 'http://www.rapidshare.com/download3'),
'megaupload' => array(
'link1' => 'http://www.megaupload.com/download1',
'link2' => 'http://www.megaupload.com/download2',
'link3' => 'http://www.megaupload.com/download3'),
'fileserve' => array(
'link1' => 'http://www.megaupload.com/download1',
'link2' => 'http://www.megaupload.com/download2',
'link3' => 'http://www.megaupload.com/download3')
);
This will do the trick: (make sure that domain is actually showing up in $domain variable though because it might be $matches[1]... I can't remember)
$newStructure = array();
foreach($links as $link) {
preg_match("/www\.([^\.])\.com/",$link,$matches);
$domain = $matches[0];
$currentLength = count($newStructure[$domain]);
if($currentLength) {
$newStructure[$domain]['link'.($currentLength+1)] = $link;
} else {
$newStructure[$domain] = array('link1'=>$link);
}
}
$server = array(
'http://www.rapidshare.com/download1',
'http://www.rapidshare.com/download2',
'http://www.rapidshare.com/download3',
'http://www.megaupload.com/download1',
'http://www.megaupload.com/download2',
'http://www.megaupload.com/download3',
'http://www.fileserve.com/download1',
'http://www.fileserve.com/download2',
'http://www.fileserve.com/download3'
);
$match = array();
$myarray = array();
foreach($server as $v) {
// grab server name
preg_match('/\.(.+)\./', $v, $match);
$serverName = $match[1];
// initialize new array if its the first link of that particular server
if (!isset($myarray[$serverName])) {
$myarray[$serverName] = array();
}
// count server array to check how many links are there, and make next link key
$linkKey = 'link' . (count($myarray[$serverName]) + 1);
// store value
$myarray[$serverName][$linkKey] = $v;
}
print_r($myarray);
Hey maybe this will help you. But i dont see the purpose of those names of the keys (link1,link2 etc..). This wont work on pagination thou.

PHP adding foreach to my array

I would like to append html to an item in my array before echoing it on my page and am unsure how to go about doing it.
My data is put into an array like so:
$query = $this->db->get();
foreach ($query->result() as $row) {
$data = array(
'seo_title' => $row->seo_title,
'seo_description' => $row->seo_description,
'seo_keywords' => $row->seo_keywords,
'category' => $row->category,
'title' => $row->title,
'intro' => $row->intro,
'content' => $row->content,
'tags' => $row->tags
);
}
return $data;
I would like to perform the following on my 'tags' before returning the data to my view:
$all_tags = explode( ',' , $row->tags );
foreach ( $all_tags as $one_tag ){
echo '' . $one_tag . '';
The reason for doing this is that the tags in my database contain no html and are simply separated by commas like so news,latest,sports and I want to convert them into
sports ...
My reason for doing this here rather than when I echo the data is that I don't want to repeat myself on every page.
You could just create a function to be used everyhwere you are including tags in your output:
function formatTags($tags) {
$tmp = explode(',', $tags);
$result = "";
foreach ($tmp as $t) {
$result .= sprintf('%s',
urlencode(trim($t)), htmlentities(trim($t)));
}
return $result;
}
And whenever you do something like echo $tags; you do echo formatTags($tags); instead. View code should be separated from model code, which is why I would advise to not put HTML inside your array.
Well first of all you're overwriting $data with every run of the loop so only the final result row will be listed.
Once that's out of the way (fix with $data[] = ...), try this:
...
'tags' => preg_replace( "/(?:^|,)([^,]+)/", "$1", $row->tags);
...

Categories