PHP function help / beginner - php

Look, if forum post have $hide_smilies is set to 1, I dont want the :p, :o to be replacen with images.
This is how I output forum post bbcode($message);
And Function:
function bbcode($str)
{
$str = htmlentities($str);
$find = array(
"/:p/",
"/:o/",
'/\[b](.*?)\[\/b]/is',
'/\[u](.*?)\[\/u]/is',
'/\[i](.*?)\[\/i]/is'
);
$replace = array(
'<img src="/images/forum/icon_tongue.gif" alt=":p" border="0" height="15" width="15">',
'<img src="/images/forum/icon_embarrassed.gif" alt=":o" border="0" height="15" width="15">'
'<strong>$1</strong>',
'<u>$1</u>',
'<i>$1</i>',
$str = preg_replace($find, $replace, $str);
return nl2br($str);
Thanks
Edit
function bbcode($str, $hide_smilies = 0)
{
$str = htmlentities($str);
$find = array(
'/\[b](.*?)\[\/b]/is',
'/\[u](.*?)\[\/u]/is',
'/\[i](.*?)\[\/i]/is',
);
$replace = array(
'<strong>$1</strong>',
'<u>$1</u>',
'<i>$1</i>'
);
if ($hide_smilies == 0)
{
$find[] = "/:p/";
$find[] = "/:o/";
$replace[] = '<img src="/images/forum/icon_tongue.gif" alt=":p" border="0" height="15" width="15">';
$replace[] = '<img src="/images/forum/icon_embarrassed.gif" alt=":o" border="0" height="15" width="15">';
}
$str = preg_replace($find, $replace, $str);
return nl2br($str);
}
This works but now (if hide_smilies=0) some characters like " gets replaced with " and so on

if hide smilies is set to 1 then just echo out $message instead of echo'ing out bbcode($message). here is a simple ternary statement that should work:
echo ($hide_smilies==1) ? $message : bbcode($message);

Just use array_slice() to chop off the unwanted bits. I'm assuming you can pass the $hide_smilies variable to the bbcode() function.
<?php
function bbcode($str, $hide_smilies=0) {
$str = htmlentities($str);
$find = array(
"/:p/",
"/:o/",
'/\[b](.*?)\[\/b]/is',
'/\[u](.*?)\[\/u]/is',
'/\[i](.*?)\[\/i]/is',
);
$replace = array(
'<img src="/images/forum/icon_tongue.gif" alt=":p" border="0" height="15" width="15">',
'<img src="/images/forum/icon_embarrassed.gif" alt=":o" border="0" height="15" width="15">',
'<strong>$1</strong>',
'<u>$1</u>',
'<i>$1</i>',
);
if ($hide_smilies) {
$find = array_slice($find, 2);
$replace = array_slice($replace, 2);
}
$str = preg_replace($find, $replace, $str);
return nl2br($str);
}
?>

If I'm understanding correctly, you still want to replace [b]'s and [i]'s with their HTML equivalents even if $hide_smilies is 1, right? In that case, initialize each array with only the non-smiley pattenrs and then add the extra elements if $hide_smilies = 1. For example:
// either pass in $hide_smilies, declare it global inside bbcode(),
// or use $_GLOBALS['hide_smilies']
function bbcode($str, $hide_smilies)
{
$str = htmlentities($str);
$find = array(
'/\[b](.*?)\[\/b]/is',
'/\[u](.*?)\[\/u]/is',
'/\[i](.*?)\[\/i]/is'
);
$replace = array(
'<strong>$1</strong>',
'<u>$1</u>',
'<i>$1</i>');
if ($hide_smilies == 1)
{
$find[] = "/:p/";
$find[] = "/:o/";
$replace[] = '<img src="/images/forum/icon_tongue.gif" alt=":p" border="0" height="15" width="15">';
$replace[] = '<img src="/images/forum/icon_embarrassed.gif" alt=":o" border="0" height="15" width="15">';
}
$str = preg_replace($find, $replace, $str);
return nl2br($str);
}

function bbcode($str)
{
$str = htmlentities($str);
$find = array(
'/\[b](.*?)\[\/b]/is',
'/\[u](.*?)\[\/u]/is',
'/\[i](.*?)\[\/i]/is'
);
$replace = array(
'<strong>$1</strong>',
'<u>$1</u>',
'<i>$1</i>',
);
$str = preg_replace($find, $replace, $str);
return nl2br($str);
}

Just add a parameter to the function and change the way you build the $find array, accordingly.
function bbcode($str, $hideSmilies = false)
{
$find = array(
'/\[b](.*?)\[\/b]/is',
'/\[u](.*?)\[\/u]/is',
'/\[i](.*?)\[\/i]/is'
);
if (!$hideSmilies)
{
$find[] = "/:p/";
$find[] = "/:o/";
}

Related

I have a problem creating a slug for the link. I want to show the numbers in the link

I have this code and it works without problems, but the numbers cannot be shown in the link. Can you help? Thank you
$title = ' domin name انا هنا & _ : 09.12.2022';
function slug($string) {
$regex = "/\.$/";
$regex = "/\.+$/";
$regex = "/[.*?:'!##$&-_ ]+$/";
$result = preg_replace($regex, "", $string);
$val= preg_replace('/\s+/u', '-', trim($result));
return strtolower($val);
}
$slugs = slug($title);
echo $slugs;
Here is something you might like to try
<?php
$title = ' domin name انا هنا & _ : 09.12.2022';
function slug($string) {
$regex = "/\.$/";
$regex = "/\.+$/";
// $regex = "/[.*?!##$&-_ ]+$/";
$result = preg_replace($regex, "", $string);
$val= preg_replace('/\s+/u', '', trim($result));
$val= preg_replace('/[.:_]+/u', '-', trim($val));
return strtolower($val);
}
echo slug($title);

Swap all youtube urls to embed via preg_replace()

Hello I'm trying to convert youtube links into embed code.
this is what I have:
<?php
$text = $post->text;
$search = '#<a(.*?)(?:href="https?://)?(?:www\.)?(?:youtu\.be/|youtube\.com(?:/embed/|/v/|/watch?.*?v=))([\w\-]{10,12}).*$#x';
$replace = '<center><iframe width="560" height="315" src="http://www.youtube.com/embed/$2" frameborder="0" allowfullscreen></iframe></center>';
$text = preg_replace($search, $replace, $text);
echo $text;
?>
It works for one link. However if I add two, it will only swap the last occurrence. What do I have to change?
You're not handling the end of the string properly. Remove the $, and replace it with the closing tag </a>. this will fix it.
$search = '#<a(.*?)(?:href="https?://)?(?:www\.)?(?:youtu\.be/|youtube\.com(?:/embed/|/v/|/watch?.*?v=))([\w\-]{10,12}).*<\/a>#x';
$replace = '<center><iframe width="560" height="315" src="http://www.youtube.com/embed/$2" frameborder="0" allowfullscreen></iframe></center>';
$text = preg_replace($search, $replace, $text);
Try this : preg_replace($search, $replace, $text, -1);
I know it's the default but who knows...
EDIT Try that if not working ;
do{
$text = preg_replace($search, $replace, $text, -1, $Count);
}
while($Count);
Here are a regular expresion more efficient: http://pregcopy.com/exp/26, tralate this to PHP: (add "s" modifier)
<?php
$text = $post->text;
$search = '#<a (?:.*?)href=["\\\']http[s]?:\/\/(?:[^\.]+\.)*youtube\.com\/(?:v\/|watch\?(?:.*?\&)?v=|embed\/)([\w\-\_]+)["\\\']#ixs';
$replace = '<center><iframe width="560" height="315" src="http://www.youtube.com/embed/$1" frameborder="0" allowfullscreen></iframe></center>';
$text = preg_replace($search, $replace, $text);
echo $text;
?>
Test it
There are two types of youtube link for one video:
Example:
$link1 = 'https://www.youtube.com/watch?v=NVcpJZJ60Ao';
$link2 = 'https://www.youtu.be/NVcpJZJ60Ao';
This function handles both:
function getYoutubeEmbedUrl($url)
{
$shortUrlRegex = '/youtu.be\/([a-zA-Z0-9_-]+)\??/i';
$longUrlRegex = '/youtube.com\/((?:embed)|(?:watch))((?:\?v\=)|(?:\/))([a-zA-Z0-9_-]+)/i';
if (preg_match($longUrlRegex, $url, $matches)) {
$youtube_id = $matches[count($matches) - 1];
}
if (preg_match($shortUrlRegex, $url, $matches)) {
$youtube_id = $matches[count($matches) - 1];
}
return 'https://www.youtube.com/embed/' . $youtube_id ;
}
The output of $link1 or $link2 would be the same :
$output1 = getYoutubeEmbedUrl($link1);
$output2 = getYoutubeEmbedUrl($link2);
// output for both: https://www.youtube.com/embed/NVcpJZJ60Ao
Now you can use the output in iframe!

PHP - replace text with smiley

I have this function:
function bb_parse($string) {
$string = $this->quote($string);
$string=nl2br($string);
$string = html_entity_decode(stripslashes(stripslashes($string)));
$tags = 'b|i|u';
while (preg_match_all('`\[('.$tags.')=?(.*?)\](.+?)\[/\1\]`', $string, $matches)) foreach ($matches[0] as $key => $match) {
list($tag, $param, $innertext) = array($matches[1][$key], $matches[2][$key], $matches[3][$key]);
switch ($tag) {
case 'b': $replacement = "<strong>$innertext</strong>"; break;
case 'i': $replacement = "<em>$innertext</em>"; break;
case 'u': $replacement = "<u>$innertext</u>"; break;
}
$string = str_replace($match, $replacement, $string);
}
return $string;
}
As you can see, I can easily make BBCode with bold, italic and underline. Although, I am trying to add smileys to this function as well, but without luck.
I tried to simply just add :) to the $tags, and then add the smiley :) img in the case, but that did not work.
How can I do, so I can also add smilies to this?
Thanks in advance.
Just create a function that does a simple str_replace, I'd say:
<?php
function smilies( $text ) {
$smilies = array(
';)' => '<img src="wink.png" />',
':)' => '<img src="smile.png" />'
);
return str_replace( array_keys( $smilies ), array_values( $smilies ), $text );
}
$string = '[b]hello[/b] smile: :)';
echo smilies( bb_parse( $string ) );
http://php.net/manual/en/function.preg-quote.php
You have to escape your smiley tags.
$tags = 'b|i|u|'.preg_quote(":)");

How to use preg_replace() to apply hilight_string() to content between BBCode-like tags?

I'm trying to run the preg_replace() function to replace the content in between two custom tags (i.e. [xcode]) within the string / content of the page.
What I want to do with the content between these custom tags is to run it through highlight_string() function and to remove those custom tags from the output.
Any idea how to do it?
So you want sort of a BBCode parser. The example below replaces [xcode] tags with whatever markup you like.
<?php
function highlight($text) {
$text = preg_replace('#\[xcode\](.+?)\[\/xcode\]#msi', '<em>\1</em>', $text);
return $text;
}
$text = '[xcode]Lorem ipsum[/xcode] dolor sit [xcode]amet[/xcode].';
echo highlight($text);
?>
Use preg_replace_callback() if you want to pass the matched text to a function:
<?php
function parse($text) {
$text = preg_replace_callback('#\[xcode\](.+?)\[\/xcode\]#msi',
function($matches) {
return highlight_string($matches[1], 1);
}
, $text);
return $text;
}
$text = '[xcode]Lorem ipsum[/xcode] dolor sit [xcode]amet[/xcode].';
echo bbcode($text);
?>
I'll include the source code of a BBCode parser that I made a long time ago. Feel free to use it.
<?php
function bbcode_lists($text) {
$pattern = "#\[list(\=(1|a))?\](.*?)\[\/list\]#msi";
while (preg_match($pattern, $text, $matches)) {
$points = explode("[*]", $matches[3]);
array_shift($points);
for ($i = 0; $i < count($points); $i++) {
$nls = split("[\n]", $points[$i]);
$brs = count($nls) - 2;
$points[$i] = preg_replace("[\r\n]", "<br />", $points[$i], $brs);
}
$replace = ($matches[2] != '1') ? ($matches[2] != 'a') ? '<ul>' : '<ol style="list-style:lower-alpha">' : '<ol style="list-style:decimal">';
$replace .= "<li>";
$replace .= implode("</li><li>", $points);
$replace .= "</li>";
$replace .= ($matches[2] == '1' || $matches[2] == 'a' ) ? '</ol>' : '</ul>';
$text = preg_replace($pattern, $replace, $text, 1);
$text = preg_replace("[\r\n]", "", $text);
}
return $text;
}
function bbcode_parse($text) {
$text = preg_replace("[\r\n]", "<br />", $text);
$smilies = Array(
':)' => 'smile.gif',
':d' => 'tongue2.gif',
':P' => 'tongue.gif',
':lol:' => 'lol.gif',
':D' => 'biggrin.gif',
';)' => 'wink.gif',
':zzz:' => 'zzz.gif',
':confused:' => 'confused.gif'
);
foreach ($smilies as $key => $value) {
$text = str_replace($key, '<img src="/images/smilies/' . $value . '" alt="' . $key . '" />', $text);
}
if (!(!strpos($text, "[") && !strpos($text, "]"))) {
$bbcodes = Array(
'#\[b\](.*?)\[/b\]#si' => '<strong>$1</strong>',
'#\[i\](.*?)\[/i\]#si' => '<em>$1</em>',
'#\[u\](.*?)\[/u\]#si' => '<span class="u">$1</span>',
'#\[s\](.*?)\[/s\]#si' => '<span class="s">$1</span>',
'#\[size=(.*?)\](.*?)\[/size\]#si' => '<span style="font-size:$1">$2</span>',
'#\[color=(.*?)\](.*?)\[/color\]#si' => '<span style="color:$1">$2</span>',
'#\[url=(.*?)\](.*?)\[/url\]#si' => '$2',
'#\[url\](.*?)\[/url\]#si' => '$1',
'#\[img\](.*?)\[/img\]#si' => '<img src="$1" alt="" />',
'#\[code\](.*?)\[/code\]#si' => '<div class="code">$1</div>'
);
$text = preg_replace(array_keys($bbcodes), $bbcodes, $text);
$text = bbcode_lists($text);
$quote_code = Array("'\[quote=(.*?)\](.*?)'i", "'\[quote](.*?)'i", "'\[/quote\]'i");
$quote_html = Array('<blockquote><p class="quotetitle">Quote \1:</p>\2', '<blockquote>\2', '</blockquote>');
$text = preg_replace($quote_code, $quote_html, $text);
}
return $text;
}
?>
basically,
preg_replace_callback('~\[tag\](.+?)\[/tag\]~', function($matches) { whatever }, $text);
this doesn't handle nested tags though
complete example
$text = "hello [xcode] <? echo bar ?> [/xcode] world";
echo preg_replace_callback(
'~\[xcode\](.+?)\[/xcode\]~',
function($matches) {
return highlight_string($matches[1], 1);
},
$text
);
<?php
$string = 'The quick brown fox jumped over the lazy dog.';
$patterns = array();
$patterns[0] = '/quick/';
$patterns[1] = '/brown/';
$patterns[2] = '/fox/';
$replacements = array();
$replacements[2] = 'bear';
$replacements[1] = 'black';
$replacements[0] = 'slow';
echo preg_replace($patterns, $replacements, $string);
?>
The above example will output:
The bear black slow jumped over the lazy dog.
http://php.net/manual/en/function.preg-replace.php
OR
str_replace should help you
http://php.net/manual/en/function.str-replace.php
Thanks to user187291's suggestion and preg_replace_callback specification I've ended up with the following outcome which does the job spot on! :
function parseTagsRecursive($input)
{
$regex = '~\[xcode\](.+?)\[/xcode\]~';
if (is_array($input)) {
$input = highlight_string($input[1], true);
}
return preg_replace_callback($regex, 'parseTagsRecursive', $input);
}
$text = "hello [xcode] <? echo bar ?> [/xcode] world and [xcode] <?php phpinfo(); ?> [/xcode]";
echo parseTagsRecursive($text);
The output of parsing the $text variable through this function is:
hello <? echo bar ?> world and <?php phpinfo(); ?>
Thank you everyone for input!

PHP function bbcode make optional to replace smileys

I want to give the oppurtunity to the user if he wants his smileys to be replaced with image smileys.
I tried this.
bbcode($text, TRUE);
function bbcode($str, $smileys = false)
{
$str = htmlentities($str);
$find = array(
if ($smileys == true) {
':p',
}
'/\[b](.*?)\[\/b]/i',
'/\[u](.*?)\[\/u]/i',
'/\[i](.*?)\[\/i]/i',
'/\[img](.*?)\[\/img]/i',
'/\[url](.*?)\[\/url]/i',
'/\[color=(.*?)\](.*?)\[\/color]/i',
'/\[size=(.*?)\](.*?)\[\/size]/i'
);
$replace = array(
if ($smileys == true) {
'<img src="/img/toungue.gif">',
}
'<strong>$1</strong>',
'<u>$1</u>',
'<i>$1</i>',
'<img src="$1" alt="$1" />',
'$1',
'<span style="color:$1">$2</span>',
'<span style="font-size:$1">$2</span>'
);
$str = preg_replace($find, $replace, $str);
return nl2br($str);
}
I guess u cant have if clause in array.
And i also tried:
function bbcode($str, $smileys = false)
{
$str = htmlentities($str);
$find = array(
'/\[b](.*?)\[\/b]/i',
'/\[u](.*?)\[\/u]/i',
'/\[i](.*?)\[\/i]/i',
'/\[img](.*?)\[\/img]/i',
'/\[url](.*?)\[\/url]/i',
'/\[color=(.*?)\](.*?)\[\/color]/i',
'/\[size=(.*?)\](.*?)\[\/size]/i'
);
$replace = array(
'<strong>$1</strong>',
'<u>$1</u>',
'<i>$1</i>',
'<img src="$1" alt="$1" />',
'$1',
'<span style="color:$1">$2</span>',
'<span style="font-size:$1">$2</span>'
);
if ($smileys == true) {
$find = array(
':p'
);
$replace = array(
'<img src="/img/toungue.gif">'
);
}
$str = preg_replace($find, $replace, $str);
return nl2br($str);
}
Equals to = No ending delimiter ':' found in functions.php on line 68
I guess u cant have if clause in array.
Yes you can, but it's called a ternary.

Categories