I have fetch this html code.
<td valign="top" style="padding:3px">
<p>
<b>Release Year: </b>2005
<br />
<b>
Genre:
<a href=/genres/Animation>Animation</a>,
<a href=/genres/Comedy>Comedy</a>
</b>
<br />
<b>External Links: </b>
IMDB
<br />
<b>No. of episodes: </b> 23 episodes
<br />
<b>Latest Episode With Links: </b>
<a title="Watch American Dad! Latest Episode (American Dad! Season 1 Episode 23)" href="/episode/american_dad_s1_e23.html">
Season 1 Episode 23 Tears of a Clooney (14/05/2006)
</a>
<br />
<div style="float: left; height: 30px; overflow: hidden; width: 100px;">
<div class="fb-like" data-href="http://watchseries.ag/season-1/american_dad" data-send="false" data-layout="button_count" data-show-faces="false"></div>
</div>
Tweet
<script>!function(d,s,id){var js,fjs=d.getElementsByTagName(s)[0],p=/^http:/.test(d.location)?'http':'https';if(!d.getElementById(id)){js=d.createElement(s);js.id=id;js.src=p+'://platform.twitter.com/widgets.js';fjs.parentNode.insertBefore(js,fjs);}}(document, 'script', 'twitter-wjs');</script>
<br clear="all" />
<b>Description :</b> The random escapades of Stan Smith, an extreme right wing CIA agent dealing with family life and keeping America safe, all in the most absurd way possible.<br>
</p>
</td>
I want only this information from above html code using php.
Only want 3 things
1.Release Year
2. Imdb Link
3. Genre
array(
'release_year'=>2005,
'imbd_link'=>'http://www.imdb.com/title/tt0397306/',
'genre'=> array(
'Animation',
'Comedy',
)
);
I have also created php function which filter html code and return me array but its not give the result like above i showed the array() its give me this result
Output
Array
(
[release year] => 2005Genre
)
function
function do_html_array($td,$dlm='<br>'){
if(!empty($td)){
$td = html_entity_decode($td);
$td = preg_replace('/<script\b[^>]*>(.*?)<\/script>/is', "", $td);
$html_array = explode($dlm,$td);
$html_key_array = array();
foreach($html_array as $key=>$html){
$html = explode(':',trim(strip_tags($html)));
if(trim($html[0])!=''){
if(count($html)<1) $html[1] = '';
if(strtolower(trim($html[0]))=='description') $html[1] = str_ireplace('[+]more','',$html[1]);
$html_key_array[strtolower(trim($html[0]))] = trim($html[1]);
switch(trim(strtolower($html[0]))){
case'external links':
preg_match_all('~<a\s+.*?</a>~is',$html_array[$key],$html_key_array['imdb_link']);
break;
case'genre':
preg_match_all('~<a\s+.*?</a>~is',$html_array[$key],$html_key_array['genre_link']);
break;
// further define here...
}
}
}
return $html_key_array;
}
return false;
}
Related
I have content that is posted from a WYSIWYG form with ajax where codes are placed between tags
stuf before content <pre class="brush: php; light: true; collapse: true; fontsize: 500; first-line: 1; ">
<?php echo "Jesus is the way the truth and the life and Jesus is Lord and He is God"; ?> </pre> stuf after content <pre class="brush: php; light: true; collapse: true; fontsize: 500; first-line: 1; ">
<?php $jesusis='Lord'; echo "Another content code"; ?> </pre>
Once the content is posted, before displaying what has been posted, on the backend I want to use the php function highlight_string to highlight every thing between the tags <pre> whether they are classes added to the tags pre like in the example above or not.
Once the content is posted, the WYSIWYG editor turns the content to htmlentities so the content becomes
<p> stuf before content <br /> </p> <pre><code><span style="color: #000000"> <br /> <?php echo "Jesus is the way the truth and the life and Jesus is Lord and He is God"; ?> <br /></span> </code></pre> <p> <br /> stuf after content <br /> </p> <pre><code><span style="color: #000000"> <br /> <?php $jesusis="Lord"; echo "Another content code"; ?> <br /></span> </code></pre> <p> <br /> </p>
So basically on the back end I want to replace <pre>...content ...</pre> with <pre>highlight_string ('content')</pre>.
In order to achieve that I first of all tried to retrieve every match between <pre>
preg_match('~<pre.*?>(.*?)</pre>~i', $content, $matches, PREG_OFFSET_CAPTURE);
//Count number of matches
$compter_matches = count($matches);
//if we have at least one match
if($compter_matches>0)
{
###############################
for($i=0; $i<$compter_matches; $i++)
{
$a_remplacer = $matches[$i];
$replacement = '<pre>'.highlight_string($a_remplacer, true).'</pre>';
$note = preg_replace('~<pre.*?>(.*?)</pre>~i', $replacement, $content);
}
##########################################
}
But when i do that i get:
int(2) Notice: Array to string conversion.
How to highlight_string content from a form within tags <pre> and </pre> using php ?
First of all your (.*?) will not match anything that spans across lines because . does not match the newline character unless you specify the s flag.
Try:
<?php
$content = '<p>
stuf before content
<br />
</p>
<pre class="brush: applescript; fontsize: 100; first-line: 1; ">
<?php echo "Jesus is the way the truth and the life and Jesus is Lord and He is God"; ?>
</pre>
<p>
<br />
stuf after content
<br />
</p>
<pre class="brush: applescript; fontsize: 100; first-line: 1; ">
<?php $jesusis="Lord"; echo "Another content code"; ?>
</pre>
<p>
<br />
</p>';
$text = preg_replace_callback(
'~<pre.*?>(.*?)</pre>~is',
function($matches) {
return('<pre>'.highlight_string(html_entity_decode($matches[1]), true).'</pre>');
},
$content
);
echo $text;
See Demo
Hmm,
What about that:
<?php
$content = '<pre>sadfasdfsadf</pre>';
$matches = array();
preg_match('~<pre.*?>(.*?)</pre>~i', $content, $matches, PREG_OFFSET_CAPTURE);
//Count number of matches
$compter_matches = count($matches);
//if we have at least one match
if($compter_matches>0)
{
for($i = 0; $i < $compter_matches; $i += 2) {
$a_remplacer = $matches[$i][0];
$replacement = '<pre>'.highlight_string($a_remplacer[$i+1][0], true).'</pre>';
$note = str_replace($a_remplacer[$i], $replacement, $content);
}
echo $note;
}
online test
This question already has answers here:
How do you parse and process HTML/XML in PHP?
(31 answers)
Closed 3 years ago.
I have a site where i get products description from database and decode html like this in PHP and display it on webpage frontend:
$data['description'] = html_entity_decode($product_info['description'], ENT_QUOTES, 'UTF-8');
It returns html like the following:
<div class="container">
<div class="textleft">
<p>
<span style="font-size:medium">
<strong>Product Name:</strong>
</span>
<br />
<span style="font-size:14px">Some description here Click here to see full details.</span>
</p>
</div>
<div class="imageblock">
<a href="some-link">
<img src="http://myproject.com/image/catalog/image1.jpg" style="width: 500px; height: 150px;" />
</a>
</div>
<div style="clear:both">
</div>
<div class="container">
<div class="textleft">
<p>
<span style="font-size:medium">
<strong>Product Name:</strong>
</span>
<br />
<span style="font-size:14px">Some description here Click here to see full details.</span>
</p>
</div>
<div class="imageblock">
<a href="some-link">
<img src="http://myproject.com/image/catalog/image2.jpg" style="width: 500px; height: 150px;" />
</a>
</div>
<div style="clear:both">
</div>
There could be many images in the product description. I have added just 2 in my example. What I need to do is replace src of every image with src="image/catalog/blank.gif" for all images and add a new attribute
data-src="http://myproject.com/image/catalog/image1.jpg"
for image 1 and
data-src="http://myproject.com/image/catalog/image2.jpg"
for image 2. data-src attribute should get the original src value of each image. How can I achieve that?
I have tried preg_replace like following
$data['description'] = preg_replace('((\n)?src="\b.*?")', 'src="image/catalog/blank.gif', $data['description']);
It replaces src attribute of every image, but how can i add data-src with original image path. I need this before page load, so is there any way to do it with PHP?
Simply adjust your regular expression. Capture the text you want using (parentheses), then reference to that group 1 using $1 or \1.
preg_replace('(src="(.*?)")', 'src="image/catalog/blank.gif" data-src="$1"', $data['description']);
Demo: https://repl.it/repls/SpottedZanyDiscussion
I think this might be what you are looking for:
http://php.net/manual/en/domdocument.getelementsbytagname.php
$data['description'] = html_entity_decode($product_info['description'], ENT_QUOTES, 'UTF-8');
$doc = new DOMDocument();
$doc->loadHTML($data['description']);
$tags = $doc->getElementsByTagName('img');
foreach ($tags as $tag) {
$old_src = $tag->getAttribute('src');
$new_src_url = 'image/catalog/blank.gif';
$tag->setAttribute('src', $new_src_url);
$tag->setAttribute('data-src', $old_src);
}
$data['description'] = $doc->saveHTML();
I havn't tested this though, so don't just copy and paste.
All pages on my bosses website initiate sessions, there is a variable on the property pages that is defined (or redefined) each time a user visits one. That variable is supposed to carry over to the contact page, where it gets inserted into the PHP contact form and sent along in an email to my boss, so that he knows which property people are contacting him about.
Here is the code I use to define the variable:
$_SESSION['property'] = "55-scholard-ph5";//Set Property Name
I have a generic PHP contact form I'm using that works fine, I also have
<?php // Start the session
session_start(); ?>
at the beginning of every page. This solution was working for about a month, but now it doesn't insert that variable.
Here is the complete HTML page code:
<!--FORM SESSION CODE-->
<?php
// Start the session
session_start();
?>
<!--FORM SESSION CODE-->
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=1100">
<title>Boris Kholodov · 55 Scollard, Penthouse 5 · Toronto, Canada</title>
<meta name="description" content="View 55 Scollard, Penthouse 5 at Boris Kholodov's real estate website.">
<link rel="stylesheet" type="text/css" href="../design.css">
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script src="../javajq/jquery.touchslider.min.js"></script>
<script>
jQuery(function($) {
$(".touchslider").touchSlider({container: this,
duration: 800, // the speed of the sliding animation in milliseconds
delay: 5000, // initial auto-scrolling delay for each loop
margin: 3, // borders size. The margin is set in pixels.
mouseTouch: true,
namespace: "touchslider",
next: ".touchslider-next", // jQuery object for the elements to which a "scroll forwards" action should be bound.
pagination: ".touchslider-nav-item",
currentClass: "touchslider-nav-item-current", // class name for current pagination item.
prev: ".touchslider-prev", // jQuery object for the elements to which a "scroll backwards" action should be bound.
autoplay: true, // Activate auto-scrolling, choose either "true" or "false"
viewport: ".touchslider-viewport"});
});
</script>
</head>
<body bgcolor="#fafbff">
<!--FORM ADDRESS CODE-->
<?php
$_SESSION['property'] = "55-scholard-ph5";//Set Property Name
?>
<!--FORM ADDRESS CODE-->
<?php include('../navigation.html');?>
<!-- MAIN CONTENT -->
<div id="page-wrap">
<!--JAVASCRIPT DISABLED NOTIFICATION-->
<noscript>
<?php include('../noscript.html');?>
</noscript>
<!---------------------------------------- MOBILE SLIDER ---------------------------------------->
<div class="touchslider hideslide" style="text-align: center;">
<div class="touchslider-viewport" style="width:1000px; height:550px; overflow:hidden; position: relative;"><div>
<div class="touchslider-item"><img src="images/55-scholard-ph5/1.jpg" class="round" width="1000" height="550" /></div>
<div class="touchslider-item"><img src="images/55-scholard-ph5/2.jpg" class="round" width="1000" height="550" /></div>
<div class="touchslider-item"><img src="images/55-scholard-ph5/3.jpg" class="round" width="1000" height="550" /></div>
<div class="touchslider-item"><img src="images/55-scholard-ph5/4.jpg" class="round" width="1000" height="550" /></div>
<div class="touchslider-item"><img src="images/55-scholard-ph5/5.jpg" class="round" width="1000" height="550" /></div>
<div class="touchslider-item"><img src="images/55-scholard-ph5/6.jpg" class="round" width="1000" height="550" /></div>
<div class="touchslider-item"><img src="images/55-scholard-ph5/7.jpg" class="round" width="1000" height="550" /></div>
<div class="touchslider-item"><img src="images/55-scholard-ph5/8.jpg" class="round" width="1000" height="550" /></div>
<div class="touchslider-item"><img src="images/55-scholard-ph5/9.jpg" class="round" width="1000" height="550" /></div>
<div class="touchslider-item"><img src="images/55-scholard-ph5/10.jpg" class="round" width="1000" height="550" /></div>
</div>
</div>
<br /><br />
<!---------------------------------------- LEAVING FOR NOW, BUT DONT NEED IT ---------------------------------------->
<div style="text-align:center; height:5px; width: 1000px; position: relative;">
<span class="touchslider-prev" style="cursor:pointer; z-index: 40;"><span class="prevbutton"></span></span>
<span class="touchslider-next" style="cursor:pointer; z-index: 40;"><span class="nextbutton"></span></span>
</div>
</div>
<!---------------------------------------- DESKTOP SLIDER ---------------------------------------->
<div id="container" class="hidephone" >
<ul>
<li><img src="images/55-scholard-ph5/1.jpg" class="round" width="1000" height="550" /></li>
<li><img src="images/55-scholard-ph5/2.jpg" class="round" width="1000" height="550" /></li>
<li><img src="images/55-scholard-ph5/3.jpg" class="round" width="1000" height="550" /></li>
<li><img src="images/55-scholard-ph5/4.jpg" class="round" width="1000" height="550" /></li>
<li><img src="images/55-scholard-ph5/5.jpg" class="round" width="1000" height="550" /></li>
<li><img src="images/55-scholard-ph5/6.jpg" class="round" width="1000" height="550" /></li>
<li><img src="images/55-scholard-ph5/7.jpg" class="round" width="1000" height="550" /></li>
<li><img src="images/55-scholard-ph5/8.jpg" class="round" width="1000" height="550" /></li>
<li><img src="images/55-scholard-ph5/9.jpg" class="round" width="1000" height="550" /></li>
<li><img src="images/55-scholard-ph5/10.jpg" class="round" width="1000" height="550" /></li>
</ul>
<span class="button prevButton"></span>
<span class="button nextButton"></span>
</div>
<img src="images/spacer.gif" class="hidephone" />
<hr class="purple">
<br />
<!----------------------------------------MAIN INFO AREA-------------------------------------->
<article>
<section>
<div class="lefttextbig">
<header>
<h1 class="black cursive">Luxury Penthouse at the Four Seasons</h1>
<br />
<h2 class="black">$1,950,000 · 55 Scollard, Penthouse 5</h2>
</header>
<p class="black">
<br />
<span class="subtitle">CANADA'S MOST PRESTIGIOUS ADDRESS </span> Yorkville. Bloor. Four Seasons. Everyone knows. This is the most prestigious and coveted address in Canada. Luxurious, stylish, seductive, the new Four Seasons Hotel Toronto has already established itself as Toronto’s most famous meeting place. Its architectural pedigree, its personality and its name have successfully attracted those from Toronto and those from abroad.
<br /><br />
<span class="subtitle">ONLY THE BEST</span> Designed by architectsAlliance in collaboration with Page & Steele this hotel condo development demonstrates a contemporary design paired with a level of elegance that will satisfy the most discerning purchaser. The private residences offer the best in design and service.
<br /><br />
<span class="subtitle">360 DEGREE LUXURY</span> Penthouse 5 is a luxuriously finished residence, measuring 1265 precious square feet, offering you 11-foot ceilings and stunning views from floor-to-ceiling windows throughout. This suite is bright, impressive, modern, yet elegant. The layout features a discreet entrance area, an open living area, split bedrooms, 2 full baths and a 20ft balcony.
<br /><br />
<span class="subtitle">ALL YOU COULD ASK FOR — AND THEN SOME</span> The east tower is a private, exclusive, resident-only building. Its owners enjoy privacy coupled with easy access to all the benefits of Four Season living, including access to hotel amenities, facilities and services. Just steps away from five-star Yorkville shops and restaurants, and central Toronto metro stations.
<br /><br />
To schedule a viewing contact Boris Kholodov.<br /><br />
</p>
<hr class="purple">
<br /><br />
<iframe src="https://www.google.com/maps/embed?pb=!1m18!1m12!1m3!1d2885.828667395075!2d-79.3884502!3d43.672532999999994!2m3!1f0!2f0!3f0!3m2!1i1024!2i768!4f13.1!3m3!1m2!1s0x882b34aedb4fae43%3A0xedbc5eb829dd0221!2s55+Scollard+St%2C+Toronto%2C+ON+M5R!5e0!3m2!1sen!2sca!4v1427829323609" width="650" height="350" frameborder="0" style="border:0"></iframe>
</div>
</section>
<!----------------------------------------MAIN INFO AREA-------------------------------------->
<!----------------------------------------DETAILED INFO---------------------------------------->
<section>
<div class="rightinfo">
<!-- Boris's Photo, Title and Contact Info-->
<?php include('boris-info.html');?>
<!-- <hr class="purple">
<p class="small">
<span class="italic">Open House Times:</span><br />
Sat 28<sup>th</sup> / 2:30pm–4:30pm<br />
Sun 1<sup>st</sup> / 2:30pm–4:30pm
</p> -->
<hr class="purple">
<a href="listing-book.php" style="text-decoration: none;">
<div class="purpleb round formstyle bgcolor sendform" style="
padding: 15px 15px 8px 15px;
width: 210px;
text-align: center;">
<span class="parastyle black" style="font-weight: normal;
letter-spacing: 0.1em;">
BOOK A SHOWING
</span>
</div>
</a>
<hr class="purple">
<a href="images/55-scholard-ph5/55-scholard-ph5-floorplan-boris.pdf" style="text-decoration: none;" target="_blank">
<div class="purpleb round formstyle bgcolor sendform" style="
padding: 15px 15px 8px 15px;
width: 210px;
text-align: center;">
<span class="parastyle black" style="font-weight: normal;
letter-spacing: 0.1em;">
VIEW FLOORPLAN
</span>
</div>
</a>
<hr class="purple">
<a href="listing-contact.php" style="text-decoration: none;">
<div class="purpleb round formstyle bgcolor sendform" style="
padding: 15px 15px 8px 15px;
width: 210px;
text-align: center;">
<span class="parastyle black" style="font-weight: normal;
letter-spacing: 0.1em;">
CONTACT BORIS
</span>
</div>
</a>
<hr class="purple">
<p class="small">
<span class="italic">Type:</span>
Downtown Penthouse
<br />
<span class="italic">Neighbourhood:</span>
Yorkville
<br />
<span class="italic">Square Footage:</span>
1265<sup>sf</sup> + Balcony
<br />
<!--<span class="italic">Lot Size:</span>
33<sup>ft</sup> × 128<sup>ft</sup>
<br /> -->
<span class="italic">Property Tax:</span>
$15,266 for 2014
<br />
<span class="italic">Bedrooms:</span>
2
<br />
<span class="italic">Washrooms:</span>
2
<br />
<span class="italic">Parking:</span>
1 Owned Underground
</p>
<hr class="purple">
<p class="small">
<span class="italic">Inclusions:</span>
<ul >
<li class="small">Miele Gas Cooktop and Oven, Sub-Zero Fridge, Panasonic Microwave, Dishwasher, Stacked Washer/Dryer</li>
<li class="small">All Existing Light Fixtures</li>
<li class="small">All Existing Window Coverings</li>
</ul>
<hr class="purple">
<p class="small">
To inquire further about this property please contact Boris.
</p>
</div>
</section>
<!----------------------------------------DETAILED INFO---------------------------------------->
</article>
<?php include('../footer.html');?>
</div>
<!-- MAIN CONTENT -->
<script src="../javajq/jquery-1.11.2.min.js"></script>
<script>
$(window).load(function(){
var pages = $('#container li'), current=0;
var currentPage,nextPage;
var timeoutID;
var buttonClicked=0;
var handler1=function(){
buttonClicked=1;
$('#container .button').unbind('click');
currentPage= pages.eq(current);
if($(this).hasClass('prevButton'))
{
if (current <= 0)
current=pages.length-1;
else
current=current-1;
}
else
{
if (current >= pages.length-1)
current=0;
else
current=current+1;
}
nextPage = pages.eq(current);
currentPage.fadeTo('slow',0.3,function(){
nextPage.fadeIn('slow',function(){
nextPage.css("opacity",1);
currentPage.hide();
currentPage.css("opacity",1);
$('#container .button').bind('click',handler1);
});
});
}
var handler2=function(){
if (buttonClicked==0)
{
$('#container .button').unbind('click');
currentPage= pages.eq(current);
if (current >= pages.length-1)
current=0;
else
current=current+1;
nextPage = pages.eq(current);
currentPage.fadeTo('slow',0.3,function(){
nextPage.fadeIn('slow',function(){
nextPage.css("opacity",1);
currentPage.hide();
currentPage.css("opacity",1);
$('#container .button').bind('click',handler1);
});
});
timeoutID=setTimeout(function(){
handler2();
}, 8000);
}
}
$('#container .button').click(function(){
clearTimeout(timeoutID);
handler1();
});
timeoutID=setTimeout(function(){
handler2();
}, 8000);
});
</script>
<!--GOOGLE TRACKING-->
<script>
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','//www.google-analytics.com/analytics.js','ga');
ga('create', 'UA-61408930-1', 'auto');
ga('send', 'pageview');
</script>
<!--GOOGLE TRACKING-->
</body>
</html>
Here is the contact form code referenced in a separate PHP document:
<?php
session_start();
if(!isset($_POST['submit']))
{
//This page should not be accessed directly. Please use the form.
echo "Error, please return to last page.";
}
$property = $_SESSION['property'];
$name = $_POST['name'];
$visitor_email = $_POST['email'];
$tel = $_POST['tel'];
$message = $_POST['message'];
$spambot = $_POST['spambot'];
if ($spambot != 'Yes') {
$spambot = 'No';
}
//Validate first
if($spambot == 'No')
{
echo "Please go back and check the 'I'm not a Spambot' box.";
exit;
}
if(empty($name)||empty($visitor_email)||empty($tel))
{
echo "Name, email and phone number are mandatory.";
exit;
}
if(IsInjected($visitor_email))
{
echo "Bad email value!";
exit;
}
// Email information
$email_from = "boris#agentboris.com";
$email_subject = "Real Estate";
$email_body =
"PROPERTY: $property \n \n".
"NAME: $name\n \n".
"MESSAGE:\n
$message \n \n ".
"PHONE NUMBER: $tel\n \n".
"EMAIL: $visitor_email\n \n".
$to = "boris#agentboris.com";
$headers = "From: $email_from \r\n";
$headers .= "Reply-To: $visitor_email \r\n";
//Send the email!
mail($to,$email_subject,$email_body,$headers);
//done. redirect to thank-you page.
header('Location: ../contact/thankyou.php');
// Function to validate against any email injection attempts
function IsInjected($str)
{
$injections = array('(\n+)',
'(\r+)',
'(\t+)',
'(%0A+)',
'(%0D+)',
'(%08+)',
'(%09+)'
);
$inject = join('|', $injections);
$inject = "/$inject/i";
if(preg_match($inject,$str))
{
return true;
}
else
{
return false;
}
}
?>
What is the problem?
You can experience the contact form by visiting this property page and clicking on any of the contact links. Please enter "community test" in the body of the form so that my boss knows its not a real client.
http://agentboris.com/listings/92-park.php
If you don't mind, I'd like to advise you not to use Session to do that, many users (like me) open multiple pages before viewing, so your property will get just the last one, sending the wrong property to your boss. Instead, you could pass this info via URL variable, changing the href property of the contact button to something like: http://agentboris.com/listings/listing-contact.php?property=55-scholard-ph5 on each page, and use the PHP $_GET["property"] in your contact's PHP code. You could use the contact form on each page too.
About the doubt of the solution stop working, make sure you aren't using #session_destroy() anywhere, neither resetting it elsewhere, sometimes I do something like: if (!$_SESSION["property"] = "") and in reality I'm resetting it to "". Certainly you are starting the session in the contact's page, right after <?php... you have to start the session to get the variable ok.
Hope it help you! Regards!
PS. you have a beautiful website!
It is the reverse of : PHP preg_replace: remove style=".." from img tags
Im trying to find an expression for preg_replace, that deletes all inline css styles except for images. For example, I have this text:
<img attribut="value" style="myCustom" attribut='value' style='myCustom' /> <input attribut="value" style="myCustom" attribut='value' style='myCustom'> <span attribut="value" style="myCustom" attribut='value' style='myCustom'> style= </span>
And I need to make it look like:
<img attribut="value" style="myCustom" attribut='value' style='myCustom' /> <input attribut="value" "myCustom" attribut='value' 'myCustom'> <span attribut="value" "myCustom" attribut='value' 'myCustom'> style= </span>
or like this:
<img attribut="value" style="myCustom" attribut='value' style='myCustom' /> <input attribut="value" attribut='value'> <span attribut="value" attribut='value'> style= </span>
It might looks like this
preg_replace('/(\<img[^>]+)(style\=\"[^\"]+\")([^>]+)(>)/', '${1}${3}${4}', $article->text)
The regex issue can be answered with a simple negative assertion:
preg_replace('/(<(?!img)\w+[^>]+)(style="[^"]+")([^>]*)(>)/', '${1}${3}${4}', $article->text)
And a simpler approach might be using querypath (rather than fiddly DOMDocument):
FORACH htmlqp($html)->find("*")->not("img") EACH $el->removeAttr("style");
This does as you've asked
$string = '<img attribut="value" style="myCustom" attribut=\'value\' style=\'myCustom\' /> <input attribut="value" style="myCustom" attribut=\'value\' style=\'myCustom\'> <span attribut="value" style="myCustom" attribut=\'value\' style=\'myCustom\'> style= </span>';
preg_match_all('/\<img.+?\/>/', $string, $images);
foreach ($images[0] as $i => $image) {
$string = str_replace($image,'--image'.$i.'--', $string);
}
$string = preg_replace(array('/style=[\'\"].+?[\'\"]/','/style=/'), '', $string);
foreach ($images[0] as $i => $image) {
$string = str_replace('--image'.$i.'--',$image, $string);
}
OUTPUTS
<img attribut="value" style="myCustom" attribut='value' style='myCustom' /> <input attribut="value" attribut='value' > <span attribut="value" attribut='value' > </span>
A very simple regular expression to get rid of them, without going too much into it would be
preg_replace( '/style="(.*)"/', 'REPLACEMENT' )
Very simple, effective enough though
this is my code:
$searchfor = array();
$searchfor[0] = 'INT.';
$searchfor[1] = 'EXT.';
// get the file contents, assuming the file to be readable (and exist)
$contents = file_get_contents($file);
// escape special characters in the query
$pattern = preg_quote($searchfor[0], '/');
// finalize the regular expression, matching the whole line
$pattern = "/^.*$pattern.*\$/m";
// search, and store all matching occurences in $matches
if(preg_match_all($pattern, $contents, $matches)){
echo "<div class='int'>".implode("\n", $matches[0])."</div>\n";
}else{
echo "No matches found";
}
How can i take the results and out each array item into an array of DIVs?
right now the output looks like this
<div class="int">INT 1</div>
INT 2
but I have like 150 instances of where INT. is found in my file so I was wanting to get it to show like this:
<div class="int" id="1">INT 1</div>
<div class="int" id="2">INT 2</div>
<div class="int" id="3">INT 3</div>
<div class="int" id="4">INT 4</div>
<div class="int" id="5">INT 5</div>
<div class="int" id="6">INT 6</div>
<div class="int" id="7">INT 7</div>
<div class="int" id="8">INT 8</div>
and so on...
Any suggestions?
UPDATED CODE:
echo '<div id="int-div" style="width: 738px; height: 100%; border: 1px solid #000; padding: 5px; background-color: #FFF;">';
$searchfor = array();
$searchfor[0] = 'INT.';
$searchfor[1] = 'EXT.';
$searchfor[2] = 'I/E.';
// get the file contents, assuming the file to be readable (and exist)
$contents = file_get_contents($file);
// escape special characters in the query
$pattern = preg_quote($searchfor[0], '/');
// finalize the regular expression, matching the whole line
$pattern = "/^.*$pattern.*\$/m";
// search, and store all matching occurences in $matches
if(preg_match_all($pattern, $contents, $matches)){
$row = 0;
foreach($matches as $match)
{
echo "<ol><li><div class='int' id='".$row."'>".implode("</div></li><li><div class='int' id='".$row."'>", $match)."</div></li></ol>\n";
$row++;
}
}else{
echo "No matches found";
}
echo '</div>';
UPDATES RESULTS:
<ol>
<li>
<div class="int" id="0">INT. STRAWBERRY'S BEDROOM - MORNING</div>
</li>
<li>
<div class="int" id="0">INT. PALO TORCIDO HIGH SCHOOL, CLASSROOM - MORNING</div>
</li>
<li>
<div class="int" id="0">INT. DUNKIN' DONUTS - MORNING</div>
</li>
<li>
<div class="int" id="0">INT. DUNKIN' DONUTS - MORNING</div>
<li>
<div class="int" id="0">INT. DUNKIN' DONUTS - EARLY MORNING (FLASHBACK)</div>
</li>
<li>
<div class="int" id="0">INT. FUENTES RESIDENCE, KITCHEN - NIGHT (PRESENT)</div>
</li>
<li>
use a foreach and use the keys as your id:
if(preg_match_all($pattern, $contents, $matches))
{
$row = 0;
foreach($matches as $match)
{
echo "<div class='int' id='".$row."'>".implode("\n", $match)."</div>\n";
$row++;
}
}else{
echo "No matches found";
}
You can avoid messy quote escaping and concatenation by creating a template string and using printf(). Notice the placeholders and the two variables that relate to them.
Code: (Demo)
$matches = [
[
"INT. STRAWBERRY'S BEDROOM - MORNING",
"INT. PALO TORCIDO HIGH SCHOOL, CLASSROOM - MORNING",
"INT. DUNKIN' DONUTS - MORNING",
"INT. DUNKIN' DONUTS - MORNING",
"INT. DUNKIN' DONUTS - EARLY MORNING (FLASHBACK)",
"INT. FUENTES RESIDENCE, KITCHEN - NIGHT (PRESENT)",
]
];
$liTemplate = <<<HTML
<li><div class="int" id="%d">%s</div></li>
HTML;
if ($matches) {
echo "<ol>\n";
foreach ($matches[0] as $i => $match) {
printf($liTemplate, $i + 1, $match);
}
echo "</ol>";
}
Output:
<ol>
<li><div class="int" id="1">INT. STRAWBERRY'S BEDROOM - MORNING</div></li>
<li><div class="int" id="2">INT. PALO TORCIDO HIGH SCHOOL, CLASSROOM - MORNING</div></li>
<li><div class="int" id="3">INT. DUNKIN' DONUTS - MORNING</div></li>
<li><div class="int" id="4">INT. DUNKIN' DONUTS - MORNING</div></li>
<li><div class="int" id="5">INT. DUNKIN' DONUTS - EARLY MORNING (FLASHBACK)</div></li>
<li><div class="int" id="6">INT. FUENTES RESIDENCE, KITCHEN - NIGHT (PRESENT)</div></li>
</ol>