correct regex synthax in custom bbcode apllication - php

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!";
}
}

Related

Php check for specific word and change color

I have never programmed in php before but I just found out that i need to edit the wp-admin page of a word press site and it MUST be done in php.
Actually what i need to do is change the color of a specific word.For example I need "cars" to be always on red. In jQuery that could be something like this:
$('p:contains("cars")').css('color', 'red');
Can anyone help me to write this in php please
You can use strpos and do something like that :
$text = "some text containing cars word";
if (strpos($text , 'cars') !== false) {
$style = 'style="color:red"';
}
else {
$style = "";
}
echo "<p ".$style.">".$text."</p>";
If the text contains "cars" word, strpos() will return the position of the word in the text. Else it will return false.
if you want to replace just words cars colored by red use preg_replace with flag g in pathern Regex to match all the words (cars) in the paragraph and replace them with red colored span. if you want change all paragraph use the code suggested by Titi
<?php
$paragraph = "<p>we all know cars faster than bikes!<p>";
echo preg_replace('/(cars)/g', '<span style="color:red;">$0</span>', $paragraph);
//<p>we all know <span style="color:red;">cars</span> faster than bikes!<p>
?>
It seems that you can use js script in the WordPress admin_enqueue_scripts.
Place your script into your plugin folder and then use it like that :
function my_enqueue($hook) {
wp_enqueue_script('my_custom_script', plugin_dir_url(__FILE__) . '/myscript.js');
}
add_action('admin_enqueue_scripts', 'my_enqueue');
This way, it calls a PHP function that calls a js file
Here is the official documentation about that : https://developer.wordpress.org/reference/hooks/admin_enqueue_scripts/
There are some posts about that at the bottom of the page.

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.

Hide Links In Forums

I've tried to hide link from none registered members, the BBcode works and it hides, but the HTML code doesn't work.
For example,
[link=http://www.brandbucket.com/]Brand Bucket[/link]
This hides well.
On the other hand..
http://www.char5.com
This doesn't hide at all, the hyperlink works fine.
Here's the code below for any help please, thanks.
$text = preg_replace("/\[file\=(.*?)\](.*?)\[\/file\]/is", $rep, $text);
$text = preg_replace("/\[link\=(.*?)\](.*?)\[\/link\]/is", $rep, $text);
$text = preg_replace("/\[url\=(.*?)\](.*?)\[\/url\]/is", $rep, $text);
$text = preg_replace("#(^|[\n ])([\w]+?://[^ \"\n\r\t<,]*)#is", "\\1".$rep, $text);
$text = preg_replace("#(^|[\n \]])((www|ftp)\.[\w+-]+?\.[\w+\-.]*(?(?=/)(/.+?(?=\s|,\s))|(?=\W)))#is", "\\1".$rep, $text);
My suggestion would be to use an if else statement and echo the elements on to the page if conditions are met.
For example on my website I have a logout button. It only shows if a user is logged in.
<?php
if(/*user is logged in*/) {
echo 'This is where the element code is placed';
}
else {
//user is not logged in so don't echo the element
}
?>
This php block will be placed inside the container element where the element you want to show would normally be. Note that if the else section of the statement is empty you can leave it out.
This can also work for a specific id or class you want to apply to an element (like changing the background colour of a div) by inserting the block where the id or class definition is.
<div id="testdiv" <?php if(/*condition*/) {echo 'class="addedclass"';} ?> ><div>

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'] . '';

Categories