SOLVED: Read the comments below #Eray.
I have a PHP function to look through text and convert text emoticons to images. :), :(, :|, etc. I also have a function that looks through text and replaces BBCode with HTML. I execute these on a string from a database. Both of these use the global variable $newtext.
emoticon($row['words']);
bb($row['words']);
echo "<b>" . $row['username'] . "</b> - " . $row['time'];
echo "<p>" . $newtext . "</p>";
echo "";
The odd thing about this, is that now (I can't remember what I did) the emoticon function doesn't work, but the bb function does. By doesn't work, I mean doesn't replace anything. Text remains text. This had worked before. Also, every few times, $newtext comes before the username. Here are my functions...
function emoticon($text)
{
global $newtext;
$newtext=str_replace(":)", "<img src='emoticons/smile.gif'>", $text);
$newtext=str_replace(":(", "<img src='emoticons/sad.gif'>", $newtext);
$newtext=str_replace(":D", "<img src='emoticons/biggrin.gif'>", $newtext);
$newtext=str_replace(":p", "<img src='emoticons/tongue.gif'>", $newtext);
$newtext=str_replace(":P", "<img src='emoticons/tongue.gif'>", $newtext);
$newtext=str_replace(":|", "<img src='emoticons/neutral.gif'>", $newtext);
$newtext=str_replace("8)", "<img src='emoticons/cool.gif'>", $newtext);
$newtext=str_replace("8D", "<img src='emoticons/cool.gif'>", $newtext);
$newtext=str_replace(":o", "<img src='emoticons/surprised.gif'>", $newtext);
$newtext=str_replace(":O", "<img src='emoticons/surprised.gif'>", $newtext);
$newtext=str_replace(";)", "<img src='emoticons/wink.gif'>", $newtext);
$newtext=str_replace("^<**>^", "<img src='emoticons/crab.gif'>", $newtext);
}
function bb($text)
{
global $newtext;
$array=array(
"[b]" => "<b>",
"[/b]" => "</b>",
"[i]" => "<i>",
"[/i]" => "</i>",
"[u]" => "<u>",
"[/u]" => "</u>",
"[big]" => "<h1>",
"[/big]" => "</h1>",
);
$newtext = str_ireplace(array_keys($array), array_values($array), $text);
}
Could you explain or help me? Also, is there a better way than using global variables? I know they can be a bit "dangerous."
function emoticon($text)
{
$smiley = array(
':)',
':(',
);
$replace = array(
"<img src='emoticons/smile.gif'>",
"<img src='emoticons/sad.gif'>",
);
return str_replace($smiley, $replace, $text);
}
I think you'd better do this:
$text = $row['words'];
$text = emoticon($text);
$text = bb($text);
echo "<b>" . $row['username'] . "</b> - " . $row['time'];
echo "<p>" . $text . "</p>";
echo "";
And then edit your functions like this:
function emoticon($text)
{
// remove this line: global $newtext;
$text=str_replace(":)", "<img src='emoticons/smile.gif'>", $text);
// etc...
$text=str_replace("^<**>^", "<img src='emoticons/crab.gif'>", $text);
return $text;
}
function bb($text)
{
// remove this line: global $newtext;
$array=array(
// etc...
);
return str_ireplace(array_keys($array), array_values($array), $text);
}
First, DEFINE your PHP functions:
function emoticon ( $string )
{
$emoticons = array( ':)' , ';)' );
$icons = ('happy.gif','wink.gif');
return str_replace( $emoticons, $icons , $string );
}
function bb( $string )
{
//BOLD [b]text[/b]
$string = preg_replace('/(\[b\]([\w\d\s\.]+)\[\/b\])/i','<b>$2</b>',$string);
//ITALIC [i]text[/i]
$string = preg_replace('/(\[i\]([\w\d\s\.]+)\[\/i\])/i','<em>$2</em>',$string);
//UNDERLINE [u]text[/u]
$string = preg_replace('/(\[u\]([\w\d\s\.]+)\[\/u\])/i','<u>$2</u>',$string);
return $string;
}
Second, Call you PHP defined functions:
echo bb( "[b]Bold[/b]" ); //Return <b>Bold</b>
Bold
echo bb( "[i]Italic[/i]" ); //Return <em>Italic</em>
Bold
echo bb( "[i]My [b]Text[/b][/i]" ); //Return <em>My <b>Text</b></em>
My Text
$var = $_POST['foo'];
echo bb( $var );
Third, Test your code:
emoticon($row['words']);
bb($row['words']);
echo "<b>" . $row['username'] . "</b> - " . $row['time'];
echo "<p>" . $newtext . "</p>";
echo "";
didnt test it but this should do:
notice that instead of using global $newtext i'm creating a local variable and return it to the outer scope via return.
function emoticon($text) {
$newtext=str_replace(":)", "<img src='emoticons/smile.gif'>", $text);
$newtext=str_replace(":(", "<img src='emoticons/sad.gif'>", $newtext);
$newtext=str_replace(":D", "<img src='emoticons/biggrin.gif'>", $newtext);
$newtext=str_replace(":p", "<img src='emoticons/tongue.gif'>", $newtext);
$newtext=str_replace(":P", "<img src='emoticons/tongue.gif'>", $newtext);
$newtext=str_replace(":|", "<img src='emoticons/neutral.gif'>", $newtext);
$newtext=str_replace("8)", "<img src='emoticons/cool.gif'>", $newtext);
$newtext=str_replace("8D", "<img src='emoticons/cool.gif'>", $newtext);
$newtext=str_replace(":o", "<img src='emoticons/surprised.gif'>", $newtext);
$newtext=str_replace(":O", "<img src='emoticons/surprised.gif'>", $newtext);
$newtext=str_replace(";)", "<img src='emoticons/wink.gif'>", $newtext);
$newtext=str_replace("^<**>^", "<img src='emoticons/crab.gif'>", $newtext);
return $newtext;
}
function bb($text) {
$array=array(
"[b]" => "<b>",
"[/b]" => "</b>",
"[i]" => "<i>",
"[/i]" => "</i>",
"[u]" => "<u>",
"[/u]" => "</u>",
"[big]" => "<h1>",
"[/big]" => "</h1>",
);
return str_ireplace(array_keys($array), array_values($array), $text);
}
$row['words'] = emoticon( $row['words'] );
$row['words'] = bb( $row['words'] );
Related
I've created a simple function that outputs an image with the correct html markup, seen below. The problem I am facing is when I pass into the alt text that has a space in it, such as "My cat is great", the alt breaks and shows alt="My" like <img src="blah.jpg" alt="My" cat is great class="home">. I'm having a hard time trying to figure this out. Any thoughts?
function image_creator($image_url, $alt=false, $class=false) {
$string = '<img src='.$image_url.' alt='.$alt.' class='.$class.'>';
return $string;
}
You're not actually outputting <img src="blah.jpg" alt="My" cat is great class="home"> - that's just how the browser is interpreting it.
You're outputting <img src=blah.jpg alt=My cat is great class=home>
You need to output some quotes:
$string = '<img src="'.$image_url.'" alt="'.$alt.'" class="'.$class.'">';
$string = "<img src='".$image_url."' alt='".$alt."' class='".$class."'>';
try this i think it will work
A little user failure. No problem!
Make sure you have your <img> tag correctly.
$image_url = 'https://example.com/image';
$alt = 'My cat is awesome';
$class = 'image';
So:
function image_creator($image_url, $alt=false, $class=false) {
$string = '<img src='.$image_url.' alt='.$alt.' class='.$class.'>';
return $string;
}
Outcome:
<img src="https://example.com/image" alt="My" cat="" is="" awesome="" class="image">
Should be:
function image_creator($image_url, $alt=false, $class=false) {
$string = '<img src="'.$image_url.'" alt="'.$alt.'" class="'.$class.'">';
return $string;
}
Outcome:
<img src="https://example.com/image" alt="My cat is awesome" class="image">
Do you see the differences? Look carefully at the quotes.
Documentation:
http://php.net/manual/en/language.types.string.php
Some examples about using quotes:
https://www.virendrachandak.com/techtalk/php-double-quotes-vs-single-quotes/
Personally I would like to use:
// $image below is being sent to the function
$image = [
'image_url' => 'https://example.com/image',
'alt' => 'My cat is awesome',
'class' => 'image',
];
function image_creator($image = [])
{
if(empty($image))
{
return 'No image';
}
return '<img src="' . $image['image_url'] . '" alt="' . $image['alt'] . '" class="' . $image['class'] . '">';
}
//Multiple solution with multiple way
$image_url = 'https://example.com/image';
$alt = 'My cat is awesome';
$class = 'image';
$string = '<img src="'.$image_url.'" alt="'.$alt.'" class="'.$class.'">';
//also you can direct echo
echo '<img src="',$image_url,'" alt="',$alt,'" class="',$class,'">';
//also you can direct echo
$string= "<img src='{$image_url}' alt='{$alt}' class='{$class}' >";
//also you can direct echo
$string = "<img src='${image_url}' alt='${alt}' class='${class}' >";
echo $string;
i want to filter value
example:
112 to be 01:12
from script
$duration = get_post_meta( $post->ID, 'TMDB_Runtime', true );
if ( ! empty( $duration ) ) {
echo '<div class="gmr-duration-item" property="duration">' . $duration . __( ' <a class="fa fa-clock-o" aria-hidden="true"></a>','movies' ) . '</div>';
I've tried using substr and str_replace and put it into function.php
<?php
$text = '$duration';
$text = substr($text, 0, 3);
echo $text =str_replace("1","01:", $text);
?>
But always display parse error.
There are two problems I am noticing in this code snippet:
<?php
$text = '$duration';
$text = substr($text, 0, 3);
echo $text =str_replace("1","01:", $text);
?>
First:
echo $text =str_replace("1","01:", $text); is incorrect syntax. You can't assign a function to a function. Split it into two lines.
$text = str_replace("1","01:", $text);
echo $text;
Second:
$text = '$duration'; is not setting $text to 112. It is setting it to the literal string $duration. Single-quotes in PHP do not evaluate variables, that is what double-quotes do. So, try this instead:
$text = "$duration";
You could do it this way, statically:
<?php
$duration = "112";
$exploded = str_split($duration);
$exploded[0] = "0".$exploded[0].":";
$final = implode($exploded);
echo $final;
?>
<?php
$xml = simplexml_load_file("xmldocumentation.xml")
or die("Error: Cannot create object");
foreach($xml->children() as $pages){
foreach($pages->children() as $page => $data){
echo $data->id;
echo '<br>';
echo $data->timestamp;
//echo $data->revision;
echo "<br />";
echo str_replace("/===[^=]+===/","bold heading here", $data->text);
echo '<p class="text">'.$data->text.'</p>';
}
}
?>
Using php how do i bold the text replaced by php's str_replace function and display the modified content with bold headings ie. ' === Heading === '?
Thanks
Change
echo str_replace("/===[^=]+===/","bold heading here", $data->text);
to
$data->text = preg_replace("/===([^=])+===/","<strong>$1</strong>", $data->text);
You need preg_replace for regex, and need to capture the text you want to bold (via the ()), and then enclose that text in an HTML element that will give you the desired formatting.
A <b> </b> can do the trick!
$strlst = 'lorem ipsum';
$strlst = explode( ' ' , $strlst );
function wrapTag($inVal){
return '<b>'.$inVal.'</b>';
}
$replace = array_map( 'wrapTag' , $strlst );
$Content = str_replace( $strlst , $replace , $Content );
echo $Content;
I am trying to replace image links, youtube video links and regular links separately with appropriate html tags and im having trouble targeting just the regular links:
Here's my code:
function($text)
{
$output = preg_replace('#(http://([^\s]*)\.(jpg|gif|png))#',
'<br/><img src="$1" alt="" width="300px" style = "clear:both;"/><br/>', $text);
$output = preg_replace('#(http://([^\s]*)youtube\.com/watch\?v=([^\s]*))#',
'<br/><iframe width="480px" height="385px" src="http://www.youtube.com/embed/$3"
frameborder="0" allowfullscreen style = "clear:both;"></iframe><br/>', $output);
$output = preg_replace('#(http://([^\s]*)\.(com))#',
'<br/>$1<br/>', $output);
return $output
}
This is instead replacing all links in the last step...how do i avoid this and replace only links (that arent youtubes or images) in the last step?
Thanks!
The urls your looking for need to be delimited by something such as spaces or new lines. Just add your delimiter to the regexes, so the the last regex is not too greedy! eg...
<?php
$text = "
http://www.youtube.com/watch?v=yQ4TPIfCK9A&feature=autoplay&list=FLBIwq18tUFrujiPd3HLPaGw&playnext=1\n
http://www.asdf.com/asdf.png\n
http://www.asdf.com\n
";
var_export($text);
var_export(replace($text));
function replace($text)
{
$output = preg_replace('#(http://([^\s]*)\.(jpg|gif|png))\n#',
'<br/><img src="$1" alt="" width="300px" style = "clear:both;"/><br/>', $text);
$output = preg_replace('#(http://([^\s]*)youtube\.com/watch\?v=([^\s]*))\n#',
'<br/><iframe width="480px" height="385px" src="http://www.youtube.com/embed/$3"
frameborder="0" allowfullscreen style = "clear:both;"></iframe><br/>', $output);
$output = preg_replace('#(http://([^\s]*)\.(com))\n#',
'<br/>$1<br/>', $output);
return $output;
}
You could use preg_replace_callback to match each link just once. So you don't have to worry about modifying a link twice:
$input = <<<EOM
http://www.example.com/fritzli.jpeg
https://www.youtube.com/watch?v=blabla+bla+"+bla
http://wwww.google.com/search?q=blabla
EOM;
echo replace($input);
function replace($text) {
$output = preg_replace_callback("#(https?://[^\s]+)#", function($umatch) {
$url = htmlspecialchars($umatch[1]);
if(preg_match("#\.(jpg|jpeg|gif|png|bmp)$#i", $url)) {
$result = "<br/><img src=\"$url\" alt=\"\" width=\"300px\" "
. " style = \"clear:both;\"/><br/>";
} elseif(preg_match("#youtube\.com/watch\?v=([^\s]+)#", $url, $match)) {
$result = "<br/><iframe width=\"480px\" height=\"385px\""
. " src=\"http://www.youtube.com/embed/{$match[1]}\""
. " frameborder=\"0\" allowfullscreen style = \"clear:both;\">"
. "</iframe><br/>";
} else {
$result = "<br/>$url<br/>";
}
return $result;
}, $text);
return $output;
}
Note: the code above works only with a PHP-version >= 5.3. If you use 5.3 or below you can just extract the inner function to a separate function and supply the function name as an argument to preg_replace_callback:
function replace_callback($umatch) {
$url = htmlspecialchars($umatch[1]);
if(preg_match("#\.(jpg|jpeg|gif|png|bmp)$#i", $url)) {
$result = "<br/><img src=\"$url\" alt=\"\" width=\"300px\" "
. " style = \"clear:both;\"/><br/>";
} elseif(preg_match("#youtube\.com/watch\?v=([^\s]+)#", $url, $match)) {
$result = "<br/><iframe width=\"480px\" height=\"385px\""
. " src=\"http://www.youtube.com/embed/{$match[1]}\""
. " frameborder=\"0\" allowfullscreen style = \"clear:both;\">"
. "</iframe><br/>";
} else {
$result = "<br/>$url<br/>";
}
return $result;
}
function replace($text) {
$output = preg_replace_callback("#(https?://[^\s]+)#",
"replace_callback", // the name of the inner function goes here
$text);
return $output;
}
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!