replacing certain images with certain words - php

i want to change the word :)) to a smily img before displaying it from database with php how can i do that

A solution would be to use the str_replace function.
For instance (Using ":-)", which I like more than your ":))" -- only a matter of taste ^^ Up to you to use the "right one") :
$str = "This is a sentence with a smiley :-)";
$new_str = str_replace(
array(
':-)',
),
array(
'<img src="smiley.png" alt=":-)" />'
),
$str
);
echo $new_str;
Will get you this output :
This is a sentence with a smiley <img src="smiley.png" alt=":-)" />
i.e. the smiley has been replaced with an image.
Note that I used an array for the first and second parameter, when calling str_replace : if you have other smileys, you can just add them to those two arrays (the first array being for the "searched" string, and the second for the "replacement").
(What I mean is : no need to call str_replace several time : one time, using arrays, should be enough for several replacements)
And, as a sidenote : I used the original "text" of the smiley for the alt attribute of the img tag : this way, if the image cannot be displayed, the browser will display the textual version of the smiley -- which is better than nothing.

You could use something like:
str_replace(':))', '<img src="path to your image" title="image title" />', $string);
If you want to replace multiple 'smileys', use arrays:
$find = array(
':)',
':('
);
$replace = array(
'<img src="path to happy image" title="" />',
'<img src="path to sad image" title="" />');
);
str_replace($find, $replace, $string);

You can use something like the following. Create a new replacement for each image you've got.
$message = str_replace(":)", "<img src='happy.png' alt=':)'/>", $message);
$message = str_replace(":(", "<img src='unhappy.png' alt=':('/>", $message);
This will turn $message "I'm happy :)" into "I'm happy <img src='happy.png' alt=':)'/>". The alt tag reveals the original smiley when users don't see images.

Related

Problems with Regular expressions in PHP

(I want to let my users tag other users with their names, problem: when someone edits his post again, he gets the link in his tinymce editor. when he saves his edits, the script will destroy the old link...)
I replace all words in a big string with words included in an array.
$users = {'this', 'car'}
$text = hello, this is <a title="this" href="">a test this</a>
$search = '!\b('.implode('|', $users).')\b!i';
$replace = '<a target="_blank" alt="$1" href="/user/$1">$1</a>';
$text = preg_replace($search, $replace, $text);
as you can see above, I try to replace 'this' and 'car' in $text with
<a target="_blank" alt="$1" href="/user/$1">$1</a>
the problem is, that my script also replaces 'this', when it's in my link:
<a title="this" href="">this</a>
im not completely sure, but I think, you know what I mean.
so my script destroys my links...
I don't need to detect, if the word is in a html element, because it should be able to replace words in other tags like h1 or p ...
I need something like
a pattern, which only matches, when the word looks like:
" this "
" this, "
",this "
" this: "...
(no problem, if i have to set these manually...)
another great solution: a string, where I can set the html tags which are not allowed.
$tags = 'a,e,article';
Greets
This should do it
<.*?this.*?>(*SKIP)(*FAIL)|\b(this)\b
Demo: https://regex101.com/r/fX0pT1/1
More on this regex approach, http://www.rexegg.com/regex-best-trick.html.
PHP Usage:
$users = array('this', 'car');
$text = 'hello, this is <a title="this" href="">a test this</a>';
$terms = '(' . implode('|', $users) . ')';
$search = '!<.*?'.$terms.'.*?>(*SKIP)(*FAIL)|\b(' . $terms . ')\b!i';
echo $search;
$replace = '<a target="_blank" alt="$2" href="/user/$2">$2</a>';
echo preg_replace($search, $replace, $text);
Output:
hello, <a target="_blank" alt="" href="/user/this">this</a> is <a title="this" href="">a test <a target="_blank" alt="" href="/user/this">this</a></a>
PHP Demo: https://eval.in/415964
...or if you only want it for links, https://regex101.com/r/fX0pT1/2, <a.*?this.*?>(*SKIP)(*FAIL)|\b(this)\b.

PHP cut text from a specific word in an HTML string

I would like to cut every text ( image alt included ) in an HTML string form a specific word.
for example this is the string:
<?php
$string = '<div><img src="img.jpg" alt="cut this text form here" />cut this text form here</div>';
?>
and this is what I would like to output
<div>
<a href="#">
<img src="img.jpg" alt="cut this text" />
cut this text
</a>
</div>
The $string is actually an element of an Object but I didn't wanted to put too long code here.
Obviously I can't use explode because that would kill the HTML markup.
And also str_replace or substr is out because the length before or after the word where it needs to be cut is not constant.
So what can I do to achive this?
Ok I solved my problem and I only post an answer to my question because it could help someone.
so this is what I did:
<?php
$string = '<div><img src="img.jpg" alt="cut this text form here" />cut this text form here</div>';
$txt_only = strip_tags($string);
$explode = explode(' from', $txt_only);
$find_txt = array(' from', $explode[1]);
$new_str = str_replace($find_txt, '', $string);
echo $new_str;
?>
This might not be the best solution but it was quick and did not involve DOM Parse.
If anybody wants to try this make sure that your href or src or any ather attribute what needs to be untouched doesn't have any of the chars in the same way and order as in $find_txt else it will replace those too.

PHP str_replace separate image from text

$item_content = '<p>'. str_replace('\n\n', '</p><p>', $item_content) .'</p>';
<?php
$item_content = '<img class="attachment-frontpage-smallthumb wp-post-image" width="140" height="80" title="Screen shot 2013-10-25 at 11.55.11 AM" alt="Screen shot 2013-10-25 at 11.55.11 AM" src="http://media.gizmodo.co.uk/wp-content/uploads/2013/10/Screen-shot-2013-10-25-at-11.55.11-AM.png">
How do you revive the Sh*t Girls Say meme that’s dead not only because we all grew tired of it, but because YouTube productivity assassins (aka movie makers) simply ran out of different types of people to make fun of? You reverse it and switch it into shit people would NEVER say. Like nerds thinking [...]
<img width="1" height="1" border="0" src="http://gizmodo.feedsportal.com/c/34920/f/644110/s/32e94f6a/sc/1/mf.gif">
<br clear="all">';
?>
I'm trying to seperate the text so that the text will get wrapped with a <p> tag but the str_replace I've gotten wraps my entire string including image with <p>
What happends if you use:
$p_pos = strpos($item_content, '<p>');
$item_content = substr($item_content, 0, $p_pos) . '<p>'. str_replace('\n', '</p>', str_replace('\n', '<p>', substr($item_content, $p_pos)) .'</p>';
That might solve your problem.
That kind of str_replace will be of no use here. And you should know that your task is not well posed. Some minimal change in HTML markup or even type of space characters (newline or not) will render previously working solution incorrect.
If text content you are willing to wrap is always in a separate line and all other lines starts with tag (like in your current sample), you can try to use logic like this:
function wrapTextLines( $content, $whichTag='p' ) {
$output = '';
foreach( explode("\n",$content) as $line ) {
$line = trim($line);
if( $line[0]!='<' )
$output .= "<{$whichTag}>{$line}</{$whichTag}>\n";
else
$output .= "{$line}\n";
}
return $output;
}
(Here it is in PHPfiddle)
Or another try is this regex, that will transform given HTML code, wrapping every text node (text between tags, containing something besides spaces) into <p> tag.
$wrapped_content = preg_replace(
'#>\s*([^\s<][^<]+)<#ms',
'><p>$1</p><',
$item_content
);
(Here it is in PHPfiddle)
Or, being more specific, will wrap every text node going after <img> tag.
$wrapped_content = preg_replace(
'#(<img[^>]+>)\s*([^\s<][^<]+)<#ims',
'$1<p>$2</p><',
$item_content
);
(Here it is in PHPfiddle)

BB Code issue PHP

Alright so I am using a little bbcode function for a forum I have, working well, so if, in example, I put
[b]Text[/b]
it will print Text in bold.
My issue is, if I have that code:
[b]
Text[/b]
Well it will not work, and just print that as it's right now.
Here is an example of the function I am using:
function BBCode ($string) {
$search = array(
'#\[b\](.*?)\[/b\]#',
);
$replace = array(
'<b>\\1</b>',
);
return preg_replace($search , $replace, $string);
}
Then when echo'ing it:
.nl2br(stripslashes(BBCode($arr_thread_row[main_content]))).
So my question would be, what is necessary so the BBcode works with everything inside it, but no necessarily on the same line.
In example:
[b]
Text
[/b]
Would simply be
Text
Thank you for any help!
Alex
You need the multiline modifier, which makes your pattern something like #\[b\](.*?)\[/b\]#ms
(note the trailing m)
There is actually a pecl extension that parses BBcode, which would be faster and more secure than writing it from scratch yourself.
I use this... It should work.
$bb1 = array(
"/\[url\](.*?)\[\/url\]/is",
"/\[img\](.*?)\[\/img\]/is",
"/\[img\=(.*?)\](.*?)\[\/img\]/is",
"/\[url\=(.*?)\](.*?)\[\/url\]/is",
"/\[red\](.*?)\[\/red\]/is",
"/\[b\](.*?)\[\/b\]/is",
"/\[h(.*?)\](.*?)\[\/h(.*?)\]/is",
"/\[php\](.*?)\[\/php\]/is"
);
$bb2 = array(
'\\1',
'<img alt="" src="\\1"/>',
'<img alt="" class="\\1" src="\\2"/>',
'<a rel="nofollow" target="_blank" href="\\1">\\2</a>',
'<span style="color:#ff0000;">\\1</span>',
'<span style="font-weight:bold;">\\1</span>',
'<h\\1>\\2</h\\3>',
'<pre><code class="php">\\1</code></pre>'
);
$html = preg_replace($bb1, $bb2, $html);

Storing a piece of the string for later use in replacement

Not sure if the subject was clear, hard to describe, easy to show:
I need to convert this:
$text = 'Bunch of text %img_Green %img_Red and some more text here';
to this:
$text = 'Bunch of text <img src="/assets/images/Green.gif" alt="Green" /> <img src="/assets/images/Red.gif" alt="Red" /> and some more text here';
Thanks in advance.
should be
$text = preg_replace('/%img_(\w+)/', '<img src="/assets/images/\1.jpg" alt="\1"/>', $text);
check out the preg_replace doc page on how this is working

Categories