HTML string remove entire line - php

I have an string that contains the body of an e-mail on html. So I need to remove one of the body lines. I made a dirty trick that work, but i guess I can found a more efficient way.
For instance I have:
<p style="background:white">
<span style="font-size:10.0pt;font-family:"Trebuchet MS","sans-serif"">
Coût element : 43.19 €.
<u></u><u></u>
</span>
</p>
And I want to remove the entire line.
I did a function that removes just the price, and stops when it fount the first letter of the next line (in that case "L"). The function:
function clear_french($body){
$value = utf8_encode(quoted_printable_decode('element'));
$ini = strpos($body,$value);
$i = 0;
if($ini === false){}
else{
while ( $body[$ini+strlen($value)+$i] != 'L' ) {
//echo $body[$ini+strlen($value)+$i];
$body[$ini+strlen($value)+$i]="";
$i++;
}
if ($body[$ini+strlen($value)+$i] == 'L'){
$body[$ini+strlen($value)+$i-1]=" ";
}
}
return $body;
}
But I don't know if there are any efficient way to do that more clean and fast. And I dunno if it should be more easy to work with text plain in $body, if it's easier how can I do it?
Note: I want to delete the cost, because I have to resent the e-mails without it.
Hope anyone helps me!
Thanks in advance.

A dirty little trick I use when I want to have placeholders and conditional parts in my HTML emails is using HTML comments. If you have control over the HTML that's sent, you can have your HTML emails set up like this :
<p style="background:white">
<span style="font-size:10.0pt;font-family:"Trebuchet MS","sans-serif"">
Coût element : <!-- __CONDITION_NAME_START__ -->43.19 €.<!-- __CONDITION_NAME_END__ -->
<u></u><u></u>
</span>
</p>
And then send the email containing the price once. (Price will appear because it is not commented)
Then you can use preg_replace to strip that part :
$newBody = preg_replace('<!-- __CONDITION_NAME_START__ -->(.|\n)*?<!-- __CONDITION_NAME_END__ -->', '', $body);
And send $newBody as your email not containing the price

I finally did it with regex, with something like taht:
$body = preg_replace('#(Translation\s+cost)\s*:\s*\d+(\.\d+)?#u', '$1:', $body);
And it works!

Related

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

preg_match for subject and body of email

I need to extract subject/body of an email message generated by a form in Joomla.
I am using some tags for defining different subjects/body for each language, like:
{lang en}English Text{/lang}
{lang it}Italian Text{/lang}
{lang fr}French Text{/lang}
I have the following code for striping Text from Subjects in different languages:
$msgSubject = $template->subject;
if ($language=='it-IT')
{
preg_match('~{lang it}([^{]*){/lang}~i', $msgSubject, $match);
$msgSubject=($match[1]);
}
elseif ($language=='en-GB')
{
preg_match('~{lang en}([^{]*){/lang}~i', $msgSubject, $match);
$msgSubject=($match[1]);
}
and so on for other languages.
It works perfectly for the subjects of the emails, which is just plain text.
If I do the same on the Body, wich is a string containing HTML elemnes like p and br, and so on, it doesn't work....
Code sample:
$msgBody = $template->body;
if ($language=='it-IT')
{
preg_match('~{lang it}([^{]*){/lang}~i', $msgBody, $match);
$msgBody=($match[1]);
}
elseif ($language=='en-GB')
{
preg_match('~{lang en}([^{]*){/lang}~i', $msgBody, $match);
$msgBody=($match[1]);
}
it simply outputs nothing. What should I change in the preg_match function to avoid mass with HTML tags?
I have checked your code and it is working fine with html code also. But i think that $msgBody containing multiple tags that you are using with joomla.
so you should use below code
preg_match_all('~{lang it}([^{]*){/lang}~i', $msgBody, $match);
because preg_match match only first occurance.
Click on preg_match_all
Is this what you want? Works for me..
http://www.phpliveregex.com/p/fkB
Edit:
If you do like this:
http://www.phpliveregex.com/p/fkF
You capture the language too and you don't need the ifs.

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.

How to replace code between the specific tags and apply php eval on it

I have a variable which calls content from database, sample is below
$content = '<div><h1>content here</h1>
<img src = 'image.jpg' /><br />
[code]echo 'welcome';[/code]
<h2>some content here</h2>
<p> some large content here</p>
[code]echo 'Click Here';[/code]
Thank you.';
echo 'headers here' .$content . 'footers here';
how can i execute PHP for the content in between [code] and [/code] tags?
remaining text would written as html execpt the codes used in [code] some php code [/code] tags
If this is for a templateting type of system for your site I would suggest to go a different route.
First your above code would change so that the portion between you code would look like:
[code]{{msg}}}[/code]
Now, you can still store your stuff in the database as php code if you want, but it makes more sense to eval it before you put it into the database, but I strongly suggest otherwise and go with a find/replace system.
Now, you would want to have a function that would do the following:
function output_template( $name, $data ) {
$template_string = get_template_from_db( $name );
for( $data as $k )
{
$template_string = str_replace( $k, $data[$k], $template_string );
}
return $template_string;
}
Then you can echo out the return value of this function. If you think you need to use eval, rethink what you are doing, especially for what appears to be a templating system.

Preserve Line Breaks From TextArea

I'm using a textarea to enable users to input comments. However, if the users enters new lines, the new lines don't appear when they are outputted. Is there any way to make the line breaks stay.
Any idea how do preserve the line breaks?
Two solutions for this:
PHP function nl2br():
e.g.,
echo nl2br("This\r\nis\n\ra\nstring\r");
// will output
This<br />
is<br />
a<br />
string<br />
Wrap the input in <pre></pre> tags.
See: W3C Wiki - HTML/Elements/pre
Here is what I use
$textToOutput = nl2br(htmlentities($text, ENT_QUOTES, 'UTF-8'));
$text is the text that needs to be displayed
$textToOutput is the returned text from nl2br and htmlentities so it can be safety displayed in the html context.
ENT_QUOTES will convert both double and single quotes, so you'll have no trouble with those.
Got my own answer: Using this function from the data from the textarea solves the problem:
function mynl2br($text) {
return strtr($text, array("\r\n" => '<br />', "\r" => '<br />', "\n" => '<br />'));
}
More here: http://php.net/nl2br
i am using this two method steps for preserve same text which is in textarea to store in mysql
and at a getting time i can also simply displaying plain text.....
step 1:
$status=$_POST['status'];<br/>
$textToStore = nl2br(htmlentities($status, ENT_QUOTES, 'UTF-8'));
In query enter $textToStore....
step 2:
write code for select query...and direct echo values....
It works
This works:
function getBreakText($t) {
return strtr($t, array('\\r\\n' => '<br>', '\\r' => '<br>', '\\n' => '<br>'));
}
function breakit($t) {
return nl2br(htmlentities($t, ENT_QUOTES, 'UTF-8'));
}
this may help you
pass the textarea wal
why make is sooooo hard people when it can be soooo easy :)
//here is the pull from the form
$your_form_text = $_POST['your_form_text'];
//line 1 fixes the line breaks - line 2 the slashes
$your_form_text = nl2br($your_form_text);
$your_form_text = stripslashes($your_form_text);
//email away
$message = "Comments: $your_form_text";
mail("destination_email#whatever.com", "Website Form Submission", $message, $headers);
you will obviously need headers and likely have more fields, but this is your textarea take care of

Categories