How to extract HTML element from a source file - php

I need to replace a HTML section identified by a tag id in a source code, which is combination of HTML and PHP using PHP. In case it's pure HTML, DOM parser could be used; in case there is no DIV in DIV, I can imagine how to use preg_match. This is what I am trying to do - I have a code (loaded into a string) like:
<div>
<img >
</div>
<? include(); ?>
<div id="mydiv">
<div>
<div>
<img >
</div>
</div>
</div>
and my task is to replace content of "mydiv" DIV with a new one e.g.
<div id="newdiv>
some text
</div>
so the string will look like this after the change:
<div>
<img >
</div>
<? include(); ?>
<div id="mydiv">
<div id="newdiv>
some text
</div>
</div>
I have already tried:
1) parsing the code using DOMdocument's loadHTML => it produces a lot of errors in case PHP code is included.
2) I played around a bit with regexes like preg_match_all('/<div id="myid"([^<]*)<\/div>/', $src, $matches), which fails in case more child divs are included.
The best approach I have found so far is:
1) find id="mydiv" string
2) search for '<' and '>' chars and count them like '<'=1 and '>'=-1 (not exactly, but it gives the idea)
3) once I get sum == 0 I should be on position of the closing tag, so I know, which portion string I should exchange
This is quite "heavy" solution, which can stop working in some cases, where the code is different (e.g. onpage PHP code contains the chars as well instead of just simple "include"). So I am looking so some better solution.

You could try something like this:
$file = 'filename.php';
$content = file_get_contents($file);
$array_one = explode( '<div id="mydiv">' , $content );
$my_div_content = explode("</div>" , $array_one[1] )[0];
Or use preg_match like you said:
preg_match('/<div id="mydiv"(.*?)<\/div>/s', $content, $matches)

Yes there is. First you need to use a function that will get the content of the file. Lets call the file homepage.php:
$homepageString = file_get_contents('homepage.php');
Now you have a string with all the content. The next thing you would do is use the preg_replace() function to take out the part of code that you want to take out:
$newHomepageString = preg_replace('/id="mydiv"/',"", $homepageString);
Now you overwrite the existing homepage.php file with the new source code:
file_put_contents("homepage.php", $newHomepageString);
Let me know if it worked for you! :)

Related

How can I split a HTML string at center of tags in PHP?

I'm trying to split a section of HTML into an array of 2 values to wrap around a template. I am trying to avoid using a placeholder but wondered if there was some way of performing something similar to the jQuery wrap() function.
So this is the code that I want to wrap:
<img src="/resources/img/photo.png">
This is the portion of HTML that I wish to wrap the image above:
<div class="container"><div class="col-md-6"></div></div>
So that the end result will be:
<div class="container">
<div class="col-md-6">
<img src="/resources/img/photo.png">
</div>
</div>
The only way that I can currently think of doing it is with a placeholder like so but would like to not have to use this method:
<div class="container"><div class="col-md-6">[REPLACE_ME]</div></div>
Any help you can give me on this would be much appreciated!
It seems to me that you pretty much have to use a placeholder if you're going to try to do this using just string manipulation. Otherwise, PHP won't really know where to put the contents within the wrapper. The [REPLACE_ME] could be done using %s in a format string for printf or sprintf.
$contents = '<img src="/resources/img/photo.png">';
$wrapper = '<div class="container"><div class="col-md-6">%s</div></div>';
// [REPLACE_ME]^
$result = sprintf($wrapper, $contents);
Here try this:
<?php
$img = '<img src="/resources/img/photo.png">';
echo '<div class="container"><div class="col-md-6">'.$img.'</div></div>';
In PHP, if you want something to show up on a page, you need to use echo. You then can concatenate a string using ..

Is it possible to change original html text in php?

I am trying to make "manner friendly" website. We use different declination dependent on gender and other factors. For example:
You did = robili
It did = robilo
She did = robila
Linguisticaly this is very simplified (and unlucky) example! I would like to change html text in php file where appropriate. For example
<? php
something
?>
html text of the page and somewhere is the word "robil"
<div>we tried to robil^i|o|a^</div>
<? php something ?>
Now I would like to replace all occurences of different tokens ^characters|characters|characters^ and replace them by one of their internal values according to "gender".
It is easy in javascript on the client side, but you will see all this weird "tokenizing" before javascript replace it.
Here I do not know the elegant solution.
Or do you have better idea?
Thanks for advice.
You can add these scripts before and after the HTML:
<?php
// start output buffering
ob_start();
?>
<html>
<body>
html text of the page and somewhere is the word "robil"
<div>we tried to robil^i|o|a^, but also vital^si|sa|ste^, borko^mal|mala|malo^ </div>
</body>
</html>
<?php
$use = 1; // indicate which declination to use (0,1 or 2)
// get buffered html
$html = ob_get_contents();
ob_end_clean();
// match anything between '^' than's not a control chr or '^', min 5 and max 20 chrs.
if (preg_match_all('/\^[^[:cntrl:]\^]{3,20}\^/',$html,$matches))
{
// replace all
foreach (array_unique($matches[0]) as $match)
{
$choices = explode('|',trim($match,'^'));
$html = str_replace($match,$choices[$use],$html);
}
}
echo $html;
This returns:
html text of the page and somewhere is the word "robil" we tried to
robilo, but also vitalsa, borkomala

convert DIV to SPAN using str_replace

I have some data that is provided to me as $data, an example of some of the data is...
<div class="widget_output">
<div id="test1">
Some Content
</div>
<ul>
<li>
<p>
<div>768hh</div>
<div>2308d</div>
<div>237ds</div>
<div>23ljk</div>
</p>
</li>
<div id="temp3">
Some more content
</div>
<li>
<p>
<div>lkgh322</div>
<div>32khhg</div>
<div>987dhgk</div>
<div>23lkjh</div>
</p>
</li>
</div>
I am attempting to change the non valid HTML DIVs inside the paragraphs so i end up with this instead...
<div class="widget_output">
<div id="test1">
Some Content
</div>
<ul>
<li>
<p>
<span>768hh</span>
<span>2308d</span>
<span>237ds</span>
<span>23ljk</span>
</p>
</li>
<div id="temp3">
Some more content
</div>
<li>
<p>
<span>lkgh322</span>
<span>32khhg</span>
<span>987dhgk</span>
<span>23lkjh</span>
</p>
</li>
</div>
I am trying to do this using str_replace with something like...
$data = str_replace('<div>', '<span>', $data);
$data = str_replace('</div>', '</span', $data);
Is there a way I can combine these two statements and also make it so that they only affect the 'This is a random item' and not the other occurences?
$data = str_replace(array('<div>', '</div>'), array('<span>', '</span>'), $data);
As long as you didn't give any other details and only asked:
Is there a way I can combine these two statements and also make it so that they only affect the 'This is a random item' and not the other occurences?
Here you go:
$data = str_replace('<div>This is a random item</div>', '<span>This is a random item</span>', $data);
You'll need to use a regular expression to do what you are looking to do, or to actually parse the string as XML and modify it that way. The XML parsing is almost surely the "safest," since as long as the string is valid XML, it will work in a predictable way. Regexes can at times fall prey to strings not being in exactly the expected format, but if your input is predictable enough, they can be ok. To do what you want with regular expressions, you'd so something like
$parsed_string = preg_replace("~<div>(?=This is a random item)(.*?)</div>~", "<span>$1</span>, $input_string);
What's happening here is the regex is looking for a <div> tag which is followed by (using a lookahead assertion) This is a random item. It then captures any text between that tag and the next </div> tag. Finally, it replaces the match with <span>, followed by the captured text from inside the div tags, followed by </span>. This will work fine on the example you posted, but will have problems if, for example, the <div> tag has a class attribute. If you are expecting things like that, either a more complex regular expression would be needed, or full XML parsing might be the best way to go.
I'm a little surprised by the other answers, I thought someone would post a good one, but that hasn't happened. str_replace is not powerful enough in this case, and regular expressions are hit-and-miss, you need to write a parser.
You don't have to write a full HTML-parser, you can cheat a bit.
$in = '<div class="widget_output">
(..)
</div>';
$lines = explode("\n", $in);
$in_paragraph = false;
foreach ($lines as $nr => $line) {
if (strstr($line, "<p>")) {
$in_paragraph = true;
} else if (strstr($line, "</p>")) {
$in_paragraph = false;
} else {
if ($in_paragraph) {
$lines[$nr] = str_replace(array('<div>', '</div>'), array('<span>', '</span>'), $line);
}
}
}
echo implode("\n", $lines);
The critical part here is detecting whether you're in a paragraph or not. And only when you're in a paragraph, do the string replacement.
Note: I'm splitting on newlines (\n) which is not perfect, but works in this case. You might want to improve this part.

Add class to html element with PHP

Is there an easy way to automatically wrap any h2 element in the div class "entry-content" in another div class "entry-header"
So the end result would look something like:
<div class="entry-content">
<div class="entry-header">
<h2>Some Title</h2>
</div>
</div>
I assume this can be done with PHP, but I'm not sure. Thanks for any input!
In terms of wordpress I would probably verge towards creating a shortcode such as
[header]Some Title[/header]
I would make the shortcode take the content and wrap the given code around it.
See some documentation here: http://codex.wordpress.org/Shortcode_API
ugly one:
$content = str_replace('<div class="entry-content">', '<div class="entry-content"><div class="entry-header">', $content);
$content = str_replace('</h2>', '</h2></div>', $content);
Can you do it in prototype ? This would be my easy solution:
var div = $('entry-content');
$(div).insert ({'top' : '<div class="entry-header">'} );
$(div).insert ({'bottom' : '</div>'} );
Maybe I'm missing somethig :)

filter php variable for specific bbcode string - wrap matches inside of divs?

hey guys,
my php variable $content holds html!
i want to filter this $content for
[q=SomeQuestoin] and [a=SomeAnswer]
and wrap each match inside of a div.question and div.answer.
So whenever this [q=Some Question][a=Some Answer] structure is found in $content i want to put out this.
<div class="qanda">
<div class="question">
Some Question
</div>
<div class="answer">
Some Answer
</div>
</div>
Is that possible? Important is that the Qustion Text or the Answer Text could hold html tags as well. like <p> or <b> etc.
update:
$q_regex = '/\[q=([^"]+?)]/is';
$q_output = '<div class="qanda"><div class="queston">$1</div>';
$content = preg_replace($q_regex, $q_output, $content);
$a_regex = '/\[a=([^"]+?)]/is';
$a_output = '<div class="answer">$1</div></div>';
$content = preg_replace($a_regex, $a_output, $content);
http://www.spotlesswebdesign.com/blog.php?id=12
tutorial on using regex to do bbcode parsing. people would recommend using a bbcode parser module however. should be safe to regex since you are not using nesting and whatnot.
EDIT
possible but tricky. could be error prone. something like this maybe:
$result = preg_replace('/\[q=(.+?)].+?\[a=(.+?)]/is', '<div class="qanda"><div class="question">$1</div><div class="answer">$2</div></div>', $subject);

Categories