Use PHP to Replace HTML with HTML - php

Is there a way to use PHP to find some HTML within a page, and replace that HTML with other HTML? I'd like for this function to be in a separate functions.php file, and look at each page on page-load for the HTML that needs replacing (unless this isn't as efficient as some other method). Thanks!

//function to add to your function definitions.
function print_processed_html($string)
{
$search = Array("--", "*", "\*", "^", "\^");
$replace = Array("<\hr>", "<b>", "<\b>", "<sup>", "<\sup>");
$processed_string = str_replace($search, $replace , $string);
echo $processed_string;
}
// outputing the string to the page.
<?php
$the_content = get_the_content();
print_processed_html($the_content);
?>
also consider reading through this http://codex.wordpress.org/Function_Reference/the_content for some tips on using the the_content() function

Related

How to make substr_replace match the whole string

<?php
$titledb = array('经济管理','管理','others');
$content='经济管理是我们国的家的中心领导力,这是中文测度。';
$replace='<a target="_blank" href="http://www.a.com/$1">$1</a>';
foreach ($titledb as $title) {
$regex = "~\b(" . preg_quote($title) . ")\b~u";
$content = preg_replace($regex, $replace, $content, 1);
}
echo $content;
?>
I was writing a auto link function for my wordpress site and I'm using substr_replace to find the keywords(which are litterally a lot) and replace it with link--I'm doing this by filtering the post content of course.
But in some circumstances, suppose there are posts with titles like "stackoverflow" and "overflow" it turns out to be a mess, the output will look like :
we love<a target="_blank" href="http://www.a.com/stackoverflow">stackoverflow</a>,this is a test。we love <a target="_blank" href="http://www.a.com/stack<a target=" _blank"="">overflow</a> ">stackoverflow,this is a test。
What I want is:
we love<a target="_blank" href="http://www.a.com/stackoverflow">stackoverflow</a>,this is a test。we love stack<a target="_blank" href="http://www.a.com/overflow">overflow</a>,this is a test。
And this is only a test.The production enviorment could be more complicated,like I said there are tens of thousands of titles as keywords need to be found and replaced with a link. So I see these broken links a lot.It happens when a title contains another title.Like title 'stackoverflow' contains another title 'overflow'.
So my question is how to make substr_replace take title 'stackoverflow' as a whole and replace only once? Of course,'overflow' still needs to be replaced somewhere else just not when it is included in another keyword.
Thank you in advance.
To prevent that a search for a word will start replacing inside the HTML code that you already injected for some other word, you could make use of a temporary placeholder, and do the final replacement on those place holders:
$titledb = array('经济管理','管理','others');
// sort the array from longer strings to smaller strings, to ensure that
// a replacement of a longer string gets precedence:
usort($titledb, function ($a,$b){ return strlen($b)-strlen($a); });
$content='经济管理是我们国的家的中心领导力。';
foreach ($titledb as $index => $title) {
$pos = strpos($content, $title);
if ($pos !== false) {
// temporarily insert a place holder in the format '#number#':
$content = substr_replace($content, "#$index#", $pos, strlen($title));
}
}
// Now replace the place holders with the final hyperlink HTML code
$content = preg_replace_callback("~#(\d+)#~u", function ($match) use ($titledb) {
return "<a target='_blank' href='http://www.a.com/{$titledb[$match[1]]}'>{$titledb[$match[1]]}</a>";
}, $content);
echo $content;
See it run on eval.in

PHP File get contents

I'm wondering if I can use file get contents to get only specific elements within the desired page. For instance: only store the content within the <title></title> tags or within the <meta></meta> tags and so forth. If it's not possible with file_get_contents what can I use to achieve that?
Thanks!
You can use explode() function;
$content = file_get_contents("http://www.demo.com");
$explodedContent = explode("<title>", $content);
$explodedExplodedContent = explode("</title>", $explodedContent[1]);
echo $explodedExplodedContent[0]; // title of that page.
You can make it into a function;
function contentBetween($beginStr, $endStr, $contentURL){
$content = file_get_contents($contentURL);
$explodedContent = explode($beginStr, $content);
$explodedExplodedContent = explode($endStr, $explodedContent[1]);
return $explodedExplodedContent[0];
}
echo contentBetween("<title>", "</title>", "http://www.demo.com"); // usage.
See more about explode() f: http://php.net/manual/tr/function.explode.php

How to use htmlspecialchars only on <code></code> tags.

I'm using WordPress and would like to create a function that applies the PHP function htmlspecialchars only to code contained between <code></code> tags. I appreciate this may be fairly simple but I'm new to PHP and can't find any references on how to do this.
So far I have the following:
function FilterCodeOnSave( $content, $post_id ) {
return htmlspecialchars($content, ENT_NOQUOTES);
}
Obviously the above is very simple and performs htmlspecialchars on the entire content of my page. I need to limit the function to only apply to the HTML between code tags (there may be multiple code tags on each page).
Any help would be appreciated.
Thanks,
James
EDIT: updated to avoid multiple CODE tags
Try this:
<?php
// test data
$textToScan = "Hi <code>test12</code><br>
Line 2 <code><br>
Test <b>Bold</b><br></code><br>
Test
";
// debug:
echo $textToScan . "<hr>";
// the regex pattern (case insensitive & multiline
$search = "~<code>(.*?)</code>~is";
// first look for all CODE tags and their content
preg_match_all($search, $textToScan, $matches);
//print_r($matches);
// now replace all the CODE tags and their content with a htmlspecialchars() content
foreach($matches[1] as $match){
$replace = htmlspecialchars($match);
// now replace the previously found CODE block
$textToScan = str_replace($match, $replace, $textToScan);
}
// output result
echo $textToScan;
?>
Use DOMDocument to get all <code> tags;
// in this example $dom is an instance of DOMDocument
$code_tags = $dom->getElementsByTagName('code');
if ($code_tags) {
foreach ($code_tags as $node) {
// [...]
}
// [...]
}
i know this is a little bit late, but you can call the htmlspecialchars function first and then when outputting call the htmlspecialchars_decode function

Using preg_replace_callback to identify and manipulate latex code

I have latex + html code somewhere in the following form:
...some text1.... \[latex-code1\]....some text2....\[latex-code2\]....etc
Firstly I want to obtain the latex codes in an array codes[] to be able to send them to a server for rendering, so that
code[0]=latex-code1, code[1]=latex-code2, etc
Secondly, I want to modify this text so that it looks like:
...some text1.... <img src="root/1.png">....some text2....<img src="root/2.png">....etc
i.e, the i-th latex code fragment is replaced by the link to the i-th rendered image.
I have been trying to do this with preg_replace_callback and preg_match_all but being new to PHP haven't been able to make it work. Please advise.
If you're looking for codez:
$html = '...some text1.... \[latex-code1\]....some text2....\[latex-code2\]....etc';
$codes = array();
$count = 0;
$replace = function($matches) use (&$codes, &$count) {
list(, $codes[]) = $matches;
return sprintf('<img src="root/%d.png">', ++$count);
};
$changed = preg_replace_callback('~\\\\\\[(.+?)\\\\\\]~', $replace, $html);
echo "Original: $html\n";
echo "Changed : $changed\n\nLatex Codes: ", print_r($codes, 1), "Count: ", $count;
I don't know at which part you've got the problems, if it's the regex pattern, you use characters inside your markers that needs heavy escaping: For PHP and PCRE, that's why there are so many slashes.
Another tricky part is the callback function because it needs to collect the codes as well as having a counter. It's done in the example with an anonymous function that has variable aliases / references in it's use clause. This makes the variables $codes and $count available inside the callback.

How to read content of one.php and write into two.php

I have one file one.php
<?php //just a php function doen't have to do any thing with the question
function B(){
}
?>
Through php I want to read one.php as it is and write into two.php as it is..
Note- '<' getting converted into '$lt;'
Answer to it is
<?php
$text = file_get_contents("one.php");
file_put_contents("two.php", $text);
?>
Now further what I want is add one more php function say function A(){} to the content of one.php and write it into two.php
That's fairly simple nowadays :-).
$text = file_get_contents("one.php");
file_put_contents("two.php", $text);
For more parameters to the methods, see the PHP.net documentation on file-get-contents and file-put-contents.
If you are after an exact copy of "one.php", then use PHP's "copy" method.
copy('one.php', 'two.php');
In regards to your edited question, the solution is:
$content = file_get_contents('one.php');
$content .= 'function A() {}';
file_put_contents('two.php', $content, FILE_APPEND);
$contents = file_get_contents('one.php');
$newContents = htmlspecialchars ($contents);
file_put_contents('two.php', $newContents);
Your are mixing up strings and resources a little bit. file_get_contents() stores the page in a string. It's easier to use file_put_contents in that case.
<?php
file_put_contents("two.php", htmlspecialchars (file_get_contents('one.php')));
// file_get_contents(): Stores the content of one.php into a string
// htmlspecialchars: encodes html
// file_put_contents(): Writes the string into two.php
?>
In your case, an even easier solution would be:
<?php
include("one.php");
?>

Categories