str_replace for multiple img classes - php

I am currently trying to use a str_replace() to replace multiple unique image classes on my site. How is this possible to do.
preg_match('/src=".+?(\.jpg)/', $image, $src);
if ($src) {
$classedImg = str_replace('<img', '<img class="plant-img" ', $image);
$src = str_replace(array('src="', '//'), array('','/'), $src[0]);
this is how it is currently set up and functioning to replace the class for all images but how would I go about doing this for multiple images setting up unique classes assigned each image.
Thank you.

If your solution doesn't require php:
Javascript
Note: you can modify the function and add arguments. I am not sure I understand the reason for why you want a unique class, but you can just increment some variable like below.
<script>
function replaceClass() {
var x = document.getElementsByClassName("targetClass");
for (var i = 0; i < x.length; i++) {
x[i].classList.add('replaceWithClass'+i); // Added the "+ i" to make unique
}
}
</script>

Related

PHP redirect but in parent frame

I have a small time url shortner at http://thetpg.tk using a simple php script and MySQL.
What it does is to get the id and matches it in the SQL Database and redirects it to the specified link found in the Database using header().
But if I have a frameset with source as something like http://thetpg.tk redirected link is loaded inside the frame instead of the parent window.
For e.g. look at the page source of
http://thetpgmusic.tk which has the frame source as
http://thetpg.tk/b which further redirects to
http://thepirategamer.tk/music.php .
I want (1) to load (3) as the parent, but just by making changes in the functions in (2) .
So is there a function like
header(Location:http://thepirategamer.tk/music.php, '_parent');
in php, or is there any other way to implement it?
NOTE: I can't change anything in (2).
Thanks in advance ! :)
There are tree solutions that can help you do this:
First solution:
This solution may involve php if you're using echo to generate your html code, when you need to output an a tag, you should make sure to add the atribute target='_parent'
<?php
echo ' Click here ';
?>
problem :
The problem with this solution, is that it doesn't work if you need to redirect in the parent window from a page that you don't own (inside the iframe). The second solution solves this problem
Second solution:
This second solution is totally client-side, wich means you need to use some javascript. you should define a javascript function that addes the target='_parent' in every a tag
function init ()
{
TagNames = document.getElementById('iframe').contentWindow.document.getElementsByTagName('a');
for( var x=0; x < TagNames.length; x++ )
TagNames[x].onclick = function()
{
this.setAttribute('target','_parent');
}
};
Now all you need to do is to call this function when the body is loaded like this
<body onload="init();"> ... </body>
problem:
The problem with this solution, is that if you have a link that contains an anchor like this href="#" it will change the parent window to the child window To solve this problem, you have to use the third solution
Third solution:
This solution is also client-side and you have to use javascript. It is like the second solution except that you have to test if the link is a url to an external page or to an anchor before you redirect. so you need to define a function that returns true if it's a link to an external page and false if it's a simple anchor, and then you'll have to use this function like this
function init ()
{
TagNames = document.getElementById('iframe').contentWindow.document.getElementsByTagName('a');
for( var x=0; x < TagNames.length; x++ )
TagNames[x].onclick = function()
{
if ( is_external_url( this.href ) )
document.location = this.href;
}
};
and you also need to call this function when the body is loaded
<body onload="init();"> ... </body>
don't forget to define is_external_url()
update :
Here is the solution to get the url of the last child, it's just a simple function that looks from frames and iframes inside the paages and get the urls
function get_last_url($url)
{
$code = file_get_contents($url);
$start = strpos($code, '<frameset');
$end = strpos($code, '</frameset>');
if($start===false||$end===false)
{
$start = strpos($code, '<iframe');
$end = strpos($code, '</iframe>');
if($start===false||$end===false)
return $url;
}
$sub = substr($code, $start,$end-$start);
$sub = substr($sub, strpos($sub,'src="')+5);
$url = explode('"', $sub)[0];
return get_last_child($url);
}
$url = get_last_url("http://thetpgmusic.tk/");
header('Location: ' . $url);
exit();

checking image size when converting BBCode text

on my mission to use ckEditor as a BBCode editor i am faced with an issue directly for my site.
I have user submitted content that can contain [img] tags.
I really want the images to have a width of 100%, which is fine. I convert any [img] tags to html and apply a class which is styled as i wish.
function basicbbcode($text) {
$text = str_replace("[IMG]", "<img class='buildimage' src='", "$text");
$text = str_replace("[/IMG]", "'>", "$text");
$text = str_replace("[img]", "<img class='buildimage' src='", "$text");
$text = str_replace("[/img]", "'>", "$text");
}
The issue is when someone uses a small / low res image. I dont wish to stretch that image because its going to look horrible.
My aim was to find a threshold, so if the image is more than 800px wide, give it the class of buildimage. If its smaller, give it a class of buildimage-small.
I would then just keep the natural size of that image. I am trying to promote the users providing high quality images but at the same time want to keep the site looking great and no having poorly stretched images because there is res is small.
So, is there a way to check the image size when it is out from the database as the $text variable and then act accordingly. Ideally with php, but maybe jquery?
No idea on this one, possible?
You can use getimagesize():
The getimagesize() function will determine the size of any given image
file and return the dimensions along with the file type and a
height/width text string to be used inside a normal HTML IMG tag and
the correspondant HTTP content type.
<?php
list($width, $height, $type, $attr) = getimagesize("img/flag.jpg");
?>
Source: http://us3.php.net/getimagesize
To do it in jQuery it could be as simple as:
var box = $("#boxWithImageInside"),
img = box.find("img.buildimage");
if (img.width() > box.width()) {
img.width("100%");
img.height("auto");
}
The code was not tested, so you may have to adjust it to to what you need.
If you want to solve your problem on client side maybe this helps : FIDDLE
$(function () {
isImgLargerThan800px = function (src) {
var img = new Image();
img.onload = function () {
if (this.width < 800) {
alert('this image need SMALL class')
} else {
alert('this image need LARGE class')
}
};
img.src = src;
};
//TEST
$('a').on('click', function () {
isImgLargerThan800px($(this).text());
alert('Now checking for image size of URL : ' + $(this).text())
})
});

Copying a Word and saving it as a Variable

I am building an online spanish dictionary. I obtain the definitions legally from another site. For specific words the user may search for, a list of suggestions comes up.
If you click on any of those suggested words, error page pops up: http://verbum.xtrweb.com/verbumpost.php?word=boedo&word0=hola . How can I make those listed words run through the code pasted below: (1) retrieve definition (2) change style.
I know that a unique URL exists for every one of those suggested words (inspect element). If you paste together that code with the original site's URL parameters, you get what I need.:
"http://lema.rae.es/drae/srv/search?id=AVNYdnea1DXX2EH9E2mb"
up to "srv/" belongs to site
the rest is from the specific word (in this case, the first suggested, "bordar"
The Process:
<?php
$words = array('word','word0','word1','word2','word3','word4','word5','word6','word7','word7','word9',
'word10','word11','word12',
'word13','word14','word15');
function url_decode($string){
return urldecode(utf8_decode($string));
}
// we'll use this later on for loading the files.
$baseUrl = 'http://lema.rae.es/drae/srv/search?val=';
// string to replace in the head.
$cssReplace = <<<EOT
<style type="text/css">
//blabla
</style>
</head>
EOT;
// string to remove in the document.
$spanRemove = '<span class="f"><b>.</b></span>';
$styleRemove =
// use for printing out the result ID.
$resultIndex = 0;
// loop through the words we defined above
// load the respective file, and print it out.
foreach($words as $word) {
// check if the request with
// the given word exists. If not,
// continue to the next word
if(!isset($_REQUEST[$word]))
continue;
// load the contents of the base url and requested word.
$contents = file_get_contents($baseUrl . urldecode(utf8_decode($_REQUEST[$word])));
// replace the data defined above.
$contents = str_replace('</head>', $cssReplace, $contents);
$contents = str_replace($spanRemove,"", $contents);
$data = preg_replace('/(search?[\d\w]+)/','http://lema.rae.es/drae/srv/\1', $data);
// print out the result with the result index.
// ++$resultIndex simply returns the value of
// $resultIndex after adding one to it.
echo "<div id='results' style='
//bla bla
}
?>
I don't think I understand your question, but I do see that you are calling preg_replace on an uninitialized variable - $data.
Maybe you want this instead?
$data = preg_replace('/(search?[\d\w]+)/','http://lema.rae.es/drae/srv/\1', $contents);
Like I said, I don't fully understand your question, but I do see that as a potential problem.
EDIT:
From your comment, it looks like you want to append the href of the link being clicked to a base url and request that page's data. Can you use jQuery? Like this:
var baseUrl = "http://lema.rae.es/drae/srv/"; // base url
//click function that binds to all anchors within a list item within a ul. in order
//to get more precise, you may need to add some classes or ids
$('ul li a').click(function(){
var src = $(this).prop('href'); //this grabs the href property of the anchor
$(this).find('span').css('propery', 'change to this'); //change css property of span child of this anchor
//or if you want to add a class with styles to the element
$(this).find('span').addClass('class name');
//ajax request to get page data
$.ajax({
type: 'POST',
url: baseUrl+src //appending the query to the base url
}).done(function(data){
//append the returned html to a div, or any element you desire
$('#myelement').append(data);
});
});
Hope this helps. If you need any help with jQuery just let me know.

Get the first image in a page with class foo

I'm trying to get the first image with specific class from page by php
<?php
$document = new DOMDocument();
#$document->loadHTML(file_get_contents('http://www.cbsnews.com/8301-501465_162-57471379-501465/first-picture-on-the-internet-turns-20/'));
$lst = $document->getElementsByTagName('img');
for ($i=0; $i<$lst->length; $i++) {
$image = $lst->item($i);
echo $image->attributes->getNamedItem('src')->value, '<br />';
}
?>
this code get all images from the page, i'm trying now to get the images with class "cnet-image" from this page
You should be able to do what you need to with Simple HTML Dom, give it a try, I've used it for several similar things including image crawlers. http://simplehtmldom.sourceforge.net/
It looks like you should be able to use the following for what you need.
// Create DOM from URL or file
$html = file_get_html('http://www.google.com/');
$ret = $html->find('img[class=foo]');
I presume that you want to retrieve the first image with a specific class attribute name in a HTML document.
If that's the case, then this could help.
var l = document.images;
var myclass = "myclass";//This is the class you want
var firstImageWithMyClass = null;
for(var i = 0; i<l; i++)
if(document.images[i].className==myclass){
firstImageWithMyClass = document.images[i];
break;
}
//Then you can see if an image with that class was found,
//then do what you want to do withit here;
if(firstImageWithMyClass!=null){
var imageSource = firstImageWithMyClass.src;
//etc, etc
}
jQuery makes this easier. Let me know if you would like to know how to do the same with jQuery and I can share with you.

A fast way (or alternate way) to dynamically load 40000 links in an image map?

I'm bringing back a GD Image which is generated from user information in a database, now on the page where this image is viewed. I have the following area map for the image generated by the same sort of query to create a link to that users profile. However, there are a possible 40000 users in the database... anyway, what I have IS working, but as you can imagine it takes a long while for it to load.
<map id="pixel" name="pixel">
<?
$map_x_1 = 0;
$map_y_1 = 0;
$map_x_2 = 5;
$map_y_2 = 5;
$block_num = 1;
while ($map_y_2 <= 1000) {
while ($map_x_2 <= 1000) {
$actual_x_cood = $map_x_1+1;
$actual_y_cood = $map_y_1+1;
$grid_search = mysql_query("SELECT *
FROM project
WHERE project_x_cood = '$actual_x_cood' AND project_y_cood = '$actual_y_cood'") or die(mysql_error());
$block_exists = mysql_num_rows($grid_search);
if ($block_exists == 1) {
echo("<area shape=\"rect\" coords=\"$map_x_1, $map_y_1, $map_x_2, $map_y_2\" href=\"/block/$block_num/\" alt=\"\" title=\"$block_num\" />\n");
} else {
echo("<area shape=\"rect\" coords=\"$map_x_1, $map_y_1, $map_x_2, $map_y_2\" href=\"/block/$block_num/\" alt=\"\" title=\"$block_num\" />\n");
}
$map_x_1 = $map_x_1 + 5;
$map_x_2 = $map_x_2 + 5;
$block_num = $block_num+1;
}
$map_y_1 = $map_y_1 + 5;
$map_y_2 = $map_y_2 + 5;
$map_x_1 = 0;
$map_x_2 = 5;
}
?>
</map>
I was thinking about just throwing in a quick jquery load screen over the top in a div and then hiding it once the page has fully loaded so it looks nicer. But I'm not really too happy with the idea of it since I would just like to load it faster.
So is there a quicker way to do it, maybe PHP? JS? Thanks!
You should consider using an input:image element. It will retreive the x-y coords as built-in functionality, and can be used in JavaScript or as part of the submission of a form.
After receiving the x-y coords, you can use a quad-tree or other algorithm for quick spacial-searching in your dataset.
you should capture the coordinates in the image map (easy with jquery) and pass it to the server which then calculates the user clicked.
i did something similar with a rate bar that hat hat 100 values (1-100%). but it was done in prototype so the code wont help you much.
small hint: i had to substract the left position of the container from the absolute click position.
in php and forms its not so flexible but far easier. you can just specify an input type image. the coordinates will be passed as post variables.
something like
will suffice

Categories