preg_match for subject and body of email - php

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.

Related

correct regex synthax in custom bbcode apllication

I wish to integrated the prism synthax highlighter into my custom built php/mysql CMS; however i am having some issues with regex synthax.
This is what i wish to accomplish:
Allow users to post
text alone,
or code and text but never code alone.
Code may be preceded by text or text may be included after the code.
My PHP Code is below:
function bbcode2html($var)
{
// [code]
$var = preg_replace('/\[code](.+?)\[\/code]/si',
'<section class="language-markup">
<pre><code>$1</code></pre>
</section>', $var);
return $var;
}
$var = '[code]<!DOCTYPE html>[/code] THis is text';
// verify content input
if(!preg_match("/(w+?)|\[code](.+?)\[\/code]/si", $var))
{
echo 'The code tags can not be empty!';
}
elseif(!preg_match("/(w+?)|\[code](.+?)\[\/code](w+)/si", $var))
{
echo 'Your post contains only code, please add some text';
}else{
echo $var = bbcode2html(htmlentities($var));}
With the present code above, this is what i have observed the following:
When text alone is posted, i get this feedback 'The code tags can not be empty!'
When text and code are posted, i get this feed back 'Your post contains only code, please add some text'
I therefore need clues as to the right regex synthax that will enable me achieve these two objectives:
Allow users to post text alone, or code and text but never code alone.
Code may be preceded by text or text may be included after the code.
Thanks.
What about doing two checks:
Verify the string contains one [[:alnum:]], after stripping all [code]...[/code] and trimming.
Check for empty code tags
See example on eval.in
$var = '[code]<!DOCTYPE html>[/code] THis is text';
// code alone or nothing
if(!preg_match('~[[:alnum:]]~', trim(preg_replace('~\[code\].*?\[/code\]~', "", $var))))
{
echo 'Please add some text...';
} else {
// empty code tags
if(preg_match('~\[code\]\s*\[/code\]~', $var))
{
echo 'The code tags can not be empty!';
// fine
} else {
echo "wohoOoo it works!";
}
}

How to get a url from a database

So I have three pages one that is the index page. One that writes the data from a form inside the index page to the database. And one that gets data from the database and echos out a html table with the data inside.
Currently if you write a link in the form. It will just come out as text. I would like the whole link to be like [link].
so say if I wrote this onto the form:
Look at this: www.google.com or Look at this: https://www.google.com
it would come out like this in html
Look at this: www.google.com
How could I go about doing this?
Okay so the html is:
<form class="wide" action="Write-to.php" method="post">
<input class="wide" autocomplete="off" name="txt" type="text" id="usermsg" style="font-size:2.4vw;" value="" />
</form>
in which the user would write:
"Look at this: www.google.com or Look at this: https://www.google.com"
This would then get sent to the database through Write-to.php.
$sql="INSERT INTO social (comunicate)
VALUES
('$_POST[txt]')";
}
this then gets written back into the database:
$result = mysqli_query($con,"(select * from social order by id desc limit {$limit_amt}) order by id asc");
while($row = mysqli_fetch_array($result))
{
echo "<tr div id='".$i."' class='border_bottom'>";
echo "<th scope='col'>";
echo "<span class='text'>".htmlspecialchars($row['comunicate'])."</span><br />";
echo "</th>";
echo "</tr>";
}
Just try:
echo(''.$your_url_variable.'');
Update:
The OP really wanted to detect url's in a string. One possible solution could be filter it using a regular expression. This code could help:
<?php
// The Regular Expression filter
$reg_exUrl = "/(http|https|ftp|ftps)\:\/\/[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(\/\S*)?/";
// The Text you want to filter for urls
$text = "The text you want to filter goes here. http://google.com";
// Check if there is a url in the text
if(preg_match($reg_exUrl, $text, $url)) {
// make the urls hyper links
echo preg_replace($reg_exUrl, "{$url[0]} ", $text);
} else {
// if no urls in the text just return the text
echo $text;
}
?>
Source: http://css-tricks.com/snippets/php/find-urls-in-text-make-links/
There are quite a few things you need to worry about when displaying user supplied (tainted) data.
You must ensure that all the data is sanitised -- never ever just echo the content, look into htmspecialchars and FILTER_VALIDATE_URL for example:
function validateUrl($url) {
return filter_var($url, FILTER_VALIDATE_URL);
}
What you are attempting to do is convert a string into a link, for example you can write a function like this:
function makeClickable($link) {
$link = htmlspecialchars($link);
return sprintf('%s', $link, $link);
}
You can use string concatenation as well, but I wouldn't do that in my view code. Just personal preference.
Take a look at the urlencode function, it will certainly come in handy.
I would also recommend you read about cross site scripting
Please note that I am not making any implementation recommendations, my aim is just to show you some contrived code samples that demonstrate making a string "clickable".
Update:
If you would like to make links clickable within text, refer to the following questions:
Best way to make links clickable in block of text
Replace URLs in text with HTML links
save the hyperlink in db and retrieve as a string by sql query
like:
select link from table_name where index = i
and save link as: whaatever here
and print it
Use this
echo '' . $res['url'] . '';

HTML string remove entire line

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!

how to remove links from a html content using php

I have the following html content:
<p>My name is way2project</p>
Now I want this text as <p>My name is way2project</p>
Is there any way to do this? Please help me thanks
I used preg_replace but in vain.
Thanks again
You can use the strip tags function
$string = '<p>My name is way2project</p>';
echo strip_tags($string,'<p>');
note the second parameter is the list of allowed tags you wont to ignore.
This seems strange, but not knowing the complete scope of your issue and seeing that you want to do this in PHP, you can try:
$origstring = '<p>My name is way2project</p>';
$newstring = str_replace('way2project', 'way2project', $origstring);
echo $newstring;
Checkout Simple Html Dom Parser
$html = str_get_html('<html><body>Hello!SO</body></html>');
echo $html->find('a',0)->innertext; //prints "SO"
strip_tags you can use this, to remove html tags.

Input of email and url to be clickable

I have a form that I process in PHP. Users sometimes put their email address in the form or URLs. These usually come out as text after I strip the input of tags.
Recently my users started asking me to make their URLs and emails clickable when they pull up a page that displays their input (now pulled from a db).
Could someone please suggest a common pattern or ways that this is handled? Basically, if someone enters a url in a form, how do I make the url clickable instead of text when viewed?
Thanks,
Alex
You can use a regular expression based function like this
function autolink($message) {
//Convert all urls to links
$message = preg_replace('#([\s|^])(www)#i', '$1http://$2', $message);
$pattern = '#((http|https|ftp|telnet|news|gopher|file|wais):\/\/[^\s]+)#i';
$replacement = '$1';
$message = preg_replace($pattern, $replacement, $message);
/* Convert all E-mail matches to appropriate HTML links */
$pattern = '#([0-9a-z]([-_.]?[0-9a-z])*#[0-9a-z]([-.]?[0-9a-z])*\\.';
$pattern .= '[a-wyz][a-z](fo|g|l|m|mes|o|op|pa|ro|seum|t|u|v|z)?)#i';
$replacement = '\\1';
$message = preg_replace($pattern, $replacement, $message);
return $message;
you have to wrap the url in a anchor tag:
assuming $myLink is the link text coming from your db:
<?php echo $myLink; ?>

Categories