extract first image and removed the first image from string - image

I have a string that has both text and images but i would like to remove the first image only using php.
$string = 'This is my test <img src="link_to_image1">, some other text.
<img src="link_to_another_image" border="0">';
$str = preg_replace('/\<img src=\"[aA-zZ0-9\/\_\.]+\"\>/','',$string, 1);

to do it using a callback. might be a little more flexible for you in case you're wanting to do stuff in the future based on images at different positions in the string
class imgReplacer {
function cb($matches){
if (!$this->counter){
$this->counter++;
return '';
} else {
return $matches[0];
}
}
}
$ir = new imgReplacer;
$ir->counter = 0;
$string = 'This is my test <img src="link_to_image1">, some other text. <img src="link_to_another_image" border="0">';
$string = preg_replace_callback(
'#(<img.*?>)#',
array(&$ir, 'cb'),
$string);
echo $string;
This is my test , some other text. <img src="link_to_another_image" border="0">

$feed_desc = preg_replace('/(<)([img])(\w+)([^>]*>)/', '', $str,1);

Related

laravel custom blade directive except tag function for htmlentites output

\Blade::directive('specialReplace', function($expression){
$expression = explode(',', $expression);
$exception = $expression[0];
$output = htmlspecialchars($expression[1]);
if ($exception == "img") {
$output = str_replace("<img", "<img", $output);
$output = str_replace("/>", "/>", $output);
} else {
$output = str_replace("<".$exception.">", "<".$exception.">",$output);
$output = str_replace("</".$exception.">", "</".$exception.">",$output);
}
return "<?PHP echo $output?>";
});
#specialReplace(img, <img src=....)
I try to make a custom function for html out image from database without htmlentites in laravel.
My problem is I get an error syntax error, unexpected '&' which I have no idea
anyone know how to fix this?
Try that, it should fix the error
return "<?PHP echo \"$output\"?>";
Also as an argument to your function, given the input
#specialReplace(img, <img src=....)
You'll receive an exact string you passed to the direcive (together with the brackets)
(img, <img src=....)
It doesn't look like you parse it properly.

Drupal 8 images with image style

In drupal 7, i use function image_style_url('style', uri) to generate new image with style and return image's path. so what will be instead of it in drupal 8? thanks
Per the change records:
use Drupal\image\Entity\ImageStyle;
$path = 'public://images/image.jpg';
$url = ImageStyle::load('style_name')->buildUrl($path);
You should try to use the new Drupal functions wherever possible.
Instead, use:
use Drupal\file\Entity\File;
use Drupal\image\Entity\ImageStyle;
$fid = 123;
$file = File::load($fid);
$image_uri = ImageStyle::load('your_style-name')->buildUrl($file->getFileUri());
Edited as per https://www.drupal.org/node/2050669:
$original_image = 'public://images/image.jpg';
// Load the image style configuration entity
use Drupal\image\Entity\ImageStyle;
$style = ImageStyle::load('thumbnail');
$uri = $style->buildUri($original_image);
$url = $style->buildUrl($original_image);
In your Controllers and other OOP part of Drupal you can use :
use Drupal\image\Entity\ImageStyle;
$path = 'public://images/image.jpg';
$url = ImageStyle::load('style_name')->buildUrl($path);
And in YOUR_THEME.theme file while Error: Class 'ImageStyle' not found in YOURTHEMENAME_preprocess_node you can do it with the follwing
$path = 'public://images/image.jpg';
$style = \Drupal::entityTypeManager()->getStorage('image_style')->load('thumbnail');
$url = $style->buildUrl($path);
Another method is provide a renderable array and let the drupal Render engine render it.
$render = [
'#theme' => 'image_style',
'#style_name' => 'thumbnail',
'#uri' => $path,
// optional parameters
];
I have found that I often want to preprocess the image to apply an image style to an image on a node or a paragraph type. In many cases I have created a paragraph that allows the user to choose the width of the image as a percentage. In the preprocess I would check the value of the width and apply the correct image style.
use Drupal\image\Entity\ImageStyle;
function THEME_preprocess_paragraph__basic_content(&$vars) {
//get the paragraph
$paragraph = $vars['paragraph'];
//get the image
$images = $paragraph->get('field_para_image');
//get the images value, in my case I only have one required image, but if you have unlimited image, you could loop thru $images
$uri = $images[0]->entity->uri->value;
//This is my field that determines the width the user wants for the image and is used to determine the image style
$preset = $paragraph->get('field_column_width')->value;
$properties = array();
$properties['title'] = $images[0]->getValue()['title'];
$properties['alt'] = $images[0]->getValue()['alt'];
//this is where the Image style is applied
switch($preset) {
case 'image-20':
$properties['uri'] = ImageStyle::load('width_20_percent')->buildUrl($uri);
break;
case 'image-45':
$properties['uri'] = ImageStyle::load('width_45_percent')->buildUrl($uri);
break;
case 'image-55':
$properties['uri'] = ImageStyle::load('width_55_percent')->buildUrl($uri);
break;
case 'image-100':
$properties['uri'] = ImageStyle::load('width_100_percent')->buildUrl($uri);
break;
}
//assign to a variable that the twig template can use
$vars['basic_image_display'] = $properties;
}
In this example, I am preprocessing a specific paragraph type named "basic_content" but you can do the same thing with a node preprocess. Continuing my example, I would have a twig template named paragraph--basic_content.html.twig to handle the display of that paragraph type.
Displaying the image would be something like this in the twig file.
<img class="img-responsive" src="{{basic_image_display['uri']}}" alt="{{ basic_image_display['alt'] }}" title="{{ basic_image_display['title'] }}"/>
$view_mode = $variables['content']['field_media_image']['0']['#view_mode'];
$display_content = \Drupal::service('entity_display.repository')
->getViewDisplay('media', 'image', $view_mode)->build($media_entity);
$style = ImageStyle::load($display_content['image'][0]['#image_style']); $original_image = $media_entity->get('image')->entity->getFileUri();
$destination = $style->buildUri($original_image);
This is how you get image style from a media image entity.
Works for me from a classic Drupal database Query in .module file :
$query = \Drupal::database()->select('file_managed', 'f' );
$query->addField('f', 'uri');
$pictures = $query->execute()->fetchAll();
foreach ($pictures as $key => $picture) {
$largePictureUri = entity_load('image_style', 'large')->buildUrl($picture->uri);
}
I used in Drupal 8 this code. It's working fine.
$fid = 374; //get your file id, this value just for example
$fname = db_select('file_managed', 'f')->fields('f', array('filename'))->condition('f.fid', $fid)->execute()->fetchField();
$url = entity_load('image_style', 'YOUR_STYLE_NAME')->buildUrl($fname);

Search specific text on a webpage using xpath

I want to search specific text on a webpage using XPath.
<?php
$url = 'http://www.barringtonsports.com/browse/hockey_sticks/show/325/list';
$html = file_get_contents($url);
$doc = new DOMDocument();
#$doc->loadHTML($html);
$xpath = new DOMXPath($doc);
$found = $xpath->evaluate("//span[contains(text(),'blablabla')]");
if(!$found){
echo "NOT FOUND";
}
else{
echo "found";
}
?>
it always give the output found as the text blablabla is not in the webpage.
where is the problem?
Is my evalute expression correct for searching specific text?
evaluate will not return a boolean for a XPath expression that selects a node, you have to use:
$found = $xpath->evaluate("boolean(//span[contains(text(),'blablabla')])");

strict with CGI::AJAX

I have set of code for updating a password in the table, here I'm using CGI::AJAX module to update the password and get the popup screen on corresponding execution.When using that code with my application it is executing properly but I didn't get the output(means Perl subroutine is not called when JavaScript function to get use.password is not updated into table). I don't get any error either.
#!/usr/bin/perl -w
use strict;
use CGI;
use DBI;
use Data::Dumper;
my $p = new CGI qw(header start_html end_html h1 script link);
use Class::Accessor;
use CGI::Ajax;
my $create_newuser;
my $ajax = new CGI::Ajax('fetch_javaScript' => $create_newuser);
print $ajax->build_html($p,\&Show_html,{-charset=>'UTF-8', -expires=>'-1d'});
sub Show_html
{
my $html = <<EOHTML;
<html>
<body bgcolor="#D2B9D3">
<IMG src="karvy.jpg" ALT="image">
<form name='myForm'>
<center><table><tr><td>
<div style="width:400px;height:250px;border:3px solid black;">
<center><h4>Create New Password's</h4>
<p>&nbsp User Name</b>&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp<INPUT TYPE="text" NAME="user" id = "user" size = "15" maxlength = "15" tabindex = "1"/></p>
<p>&nbsp Password:</b>&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp<INPUT TYPE=PASSWORD NAME="newpassword" id = "newpassword" size = "15" maxlength = "15" tabindex = "1"/></p>
<p>&nbsp Re-Password:</b>&nbsp&nbsp&nbsp<INPUT TYPE=PASSWORD NAME="repassword" id = "repassword" size = "15" maxlength = "15" tabindex = "1"/></p>
<input type="submit" id="val" value="Submit" align="middle" method="GET" onclick="fetch_javaScript(['user','newpassword','repassword']);"/><INPUT TYPE="reset" name = "Reset" value = "Reset"/>
<p>Main Menu <A HREF = login.pl>click here</A>
</center>
</div>
</td></tr></table></center>
</form>
</body>
</html>
EOHTML
return $html;
}
$create_newuser =sub
{
my #input = $p->params('args');
my $user=$input[0];
my $password=$input[1];
my $repassword=$input[2];
my $DSN = q/dbi:ODBC:SQLSERVER/;
my $uid = q/123/;
my $pwd = q/123/;
my $DRIVER = "Freetds";
my $dbh = DBI->connect($DSN,$uid,$pwd) or die "Coudn't Connect SQL";
if ($user ne '')
{
if($password eq $repassword)
{
my $sth=$dbh->do("insert into rpt_account_information (user_id,username,password,user_status,is_admin) values(2,'".$user."','".$password."',1,1)");
my $value=$sth;
print $value,"\n";
if($value == 1)
{
print 'Your pass has benn changed.Return to the main page';
}
}
else
{
print "<script>alert('Password and Re-Password does not match')</script>";
}
}
else
{
print "<script>alert('Please Enter the User Name')</script>";
}
}
my $create_newuser;
my $ajax = new CGI::Ajax('fetch_javaScript' => $create_newuser);
...;
$create_newuser =sub { ... };
At the moment when you create a new CGI::Ajax object, the $create_newuser variable is still undef. Only much later do you assign a coderef to it.
You can either assign the $create_newuser before you create the CGI::Ajax:
my $create_newuser =sub { ... };
my $ajax = new CGI::Ajax('fetch_javaScript' => $create_newuser);
...;
Or you use a normal, named subroutine and pass a coderef.
my $ajax = new CGI::Ajax('fetch_javaScript' => \&create_newuser);
...;
sub create_newuser { ... }
Aside from this main error, your script has many more problems.
You should use strict instead of the -w option.
For debugging purposes only, use CGI::Carp 'fatalsToBrowser' and sometimes even with warningsToBrowser can be extremely helpful. Otherwise, keeping a close eye on the error logs is a must.
my $p = new CGI qw(header start_html end_html h1 script link) doesn't make any sense. my $p = CGI->new should be sufficient.
use Class::Accessor seems a bit random here.
The HTML in Show_html is careless. First, your heredocs allows variable interpolation and escape codes – it has the semantics of a double quoted string. Most of the time, you don't want that. Start a heredoc like <<'END_OF_HTML' to avoid interpolation etc.
Secondly, look at that tag soup you are producing! Here are some snippets that astonish me:
bgcolor="#D2B9D3", align="middle" – because CSS hasn't been invented yet.
<center> – because CSS hasn't been invented yet, and this element isn't deprecated at all.
<table><tr><td><div ... </div></td></tr></table> – because there is nothing wrong with a table containing a single cell. (For what? This isn't even for layout reasons!) This table cell contains a single div …
… which contains another center. Seriously, what is so great about unneccessary DOM elements that CSS isn't even an option.
style="width:400px;height:250px;border:3px solid black;" – because responsive design hasn't been invented yet.
<p> ... </b> – Oh, what delicious tag soup!
&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp – this isn't a typewriter, you know. Use CSS and proper markup for your layout. There is a difference between text containing whitespace, and empty areas in your layout.
tabindex = "1" … tabindex = "1" … tabindex = "1" – I don't think you know what tabindex does.
<A HREF = login.pl> – LOWERCASING OR QUOTING YOUR ATTRIBUTES IS FOR THE WEAK!!1
onclick="fetch_javaScript(['user','newpassword','repassword']);" – have you read the CGI::Ajax docs? This is not how it works: You need to define another argument with the ID of the element where the answer HTML is displayed.
In your create_newuser, you have an SQL injection vulnerability. Use placeholders to solve that. Instead of $sth->do("INSERT INTO ... VALUES('$foo')") use $sth->do('INSERT INTO ... VALUES(?)', $foo).
print ... – your Ajax handler shouldn't print output, instead it should return a HTML string, which then gets hooked into the DOM at the place your JS function specified. You want something like
use HTML::Entities;
sub create_newuser {
my ($user, $password, $repassword) = $p->params('args');
my ($e_user, $e_password) = map { encode_entities($_) } $user, $password;
# DON'T DO THIS, it is a joke
return "Hello <em>$e_user</em>, your password <code>$e_password</code> has been successfully transmitted in cleartext!";
}
and in your JS:
fetch_javaScript(['user','newpassword','repassword'], ['answer-element'], 'GET');
where your HTML document somewhere has a <div id="answer-element" />.

filename and contenttype of upload image

how to get the name of the file and the content type of the image which we uploaded in mvc application please tell me its urgent
thanks
ritz
May be below code will be helpful..
//index..
<?php
require_once("include/DBConnect.php");
include_once('header.php');
?>
<div align="center">
<h1 style="color:red">Welcome </h1>
<br/>
<form action="upload.php" method="post" enctype="multipart/form-data" id="UploadForm">
<input name="ImageFile" type="file" />
<input type="submit" id="SubmitButton" value="Upload" />
</form>
</div>
<?php include_once('footer.php');?>
//upload
<?php
require_once("include/DBConnect.php");
require_once("include/FunctionGeneral.php");
include_once('header.php');
if(isset($_POST))
{
$ThumbSquareSize = 200; //Thumbnail will be 200x200
$BigImageMaxSize = 500; //Image Maximum height or width
$ThumbPrefix = "thumb_"; //Normal thumb Prefix
$DestinationDirectory = 'uploads/'; //Upload Directory ends with / (slash)
$Quality = 90;
// check $_FILES['ImageFile'] array is not empty
if(!isset($_FILES['ImageFile']) || !is_uploaded_file($_FILES['ImageFile']['tmp_name']))
{
die('Something went wrong with Upload!'); // output error .
}
// Random number for both file, will be added after image name
$RandomNumber = rand(0, 9999999999);
// Elements (values) of $_FILES['ImageFile'] array
//let's access these values by using their index position
$ImageName = str_replace(' ','-',strtolower($_FILES['ImageFile']['name']));
$ImageSize = $_FILES['ImageFile']['size']; // Obtain original image size
$TempSrc = $_FILES['ImageFile']['tmp_name']; // Tmp name of image file stored in PHP tmp folder
$ImageType = $_FILES['ImageFile']['type']; //Obtain file type, returns "image/png", image/jpeg, text/plain etc.
switch(strtolower($ImageType))
{
case 'image/png':
$CreatedImage = imagecreatefrompng($_FILES['ImageFile']['tmp_name']);
break;
case 'image/gif':
$CreatedImage = imagecreatefromgif($_FILES['ImageFile']['tmp_name']);
break;
case 'image/jpeg':
case 'image/pjpeg':
$CreatedImage = imagecreatefromjpeg($_FILES['ImageFile']['tmp_name']);
break;
default:
die('Unsupported File!'); //output error and exit
}
//PHP getimagesize() function returns height-width from image file stored in PHP tmp folder.
list($CurWidth,$CurHeight)=getimagesize($TempSrc);
//Get file extension from Image name, this will be re-added after random name
$ImageExt = substr($ImageName, strrpos($ImageName, '.'));
$ImageExt = str_replace('.','',$ImageExt);
//remove extension from filename
$ImageName = preg_replace("/\\.[^.\\s]{3,4}$/", "", $ImageName);
//Construct a new image name (with random number added) for our new image.
$NewImageName = $ImageName.'-'.$RandomNumber.'.'.$ImageExt;
//set the Destination Image
$thumb_DestRandImageName = $DestinationDirectory.'thumbnail/'.$ThumbPrefix.$NewImageName; //Thumb name
$DestRandImageName = $DestinationDirectory.$NewImageName; //Name for Big Image
//Resize image to our Specified Size by calling resizeImage function.
if(resizeImage($CurWidth,$CurHeight,$BigImageMaxSize,$DestRandImageName,$CreatedImage,$Quality,$ImageType))
{
//Create a square Thumbnail right after, this time we are using cropImage() function
if(!cropImage($CurWidth,$CurHeight,$ThumbSquareSize,$thumb_DestRandImageName,$CreatedImage,$Quality,$ImageType))
{
echo 'Error Creating thumbnail';
}
/*
At this point we have succesfully resized and created thumbnail image
We can render image to user's browser or store information in the database
For demo, we are going to output results on browser.
*/
echo '<div id="output">';
echo '<table width="100%" border="0" cellpadding="4" cellspacing="0">';
echo '<tr>';
echo '<td align="center"><img src="'.$thumb_DestRandImageName.'" alt="Thumbnail"></td>';
echo '</tr><tr>';
echo '<td align="center"><img src="'.$DestRandImageName.'" alt="Resized Image"></td>';
echo '</tr>';
echo '</table>';
echo '</div>';
/*
// Insert info into database table!
mysql_query("INSERT INTO myImageTable (ImageName, ThumbName, ImgPath)
VALUES ($DestRandImageName, $thumb_DestRandImageName, 'uploads/')");
*/
$added = getCurDate();
$title = "test";//$dbObj->escape_special_char($_POST['title']);
session_start();
$_SESSION['user_id'] = "rakhi";
$user_id = $_SESSION['user_id'];
$fields = "`photo_title` ,`createuser` ,`image_name` ,`added`";
$values = "'$title','$user_id','$NewImageName','$added'";
}else{
die('Resize Error'); //output error
}
}
include_once('footer.php');
?>

Resources