I would like to change all emoticons codes from my string to emoticons images.
Here is my array with codes and URLs:
$smilies = array(
array('http://page.com/facebook-smiley-face-for-comments.png', ':)'),
array('http://page.com/big-smile-emoticon-for-facebook.png', ':D'),
array('http://page.com/facebook-frown-emoticon.png', ':('),
...
);
and here is script which change this codes for images:
foreach($smilies as $emoticon)
{
$quoted_emoticon = preg_quote($emoticon[1],"#");
$match = '#(?!<\w)(' . $quoted_emoticon .')(?!\w)#';
$message = preg_replace($match,'<img src="'.$emoticon[0].'">',$message);
}
But I have one problem with that. I would like to change code for image only when emoticon code have space - before emoticon code and after emoticon code - example:
Here is text :--) with emoticon.
I would like to change also code for image when emoticon is at the end of string. Then emoticon code should have added only space before code:
Here is text with emoticon :--)
And the same situation with the begininnig of a string - emoticon code should have added only space after code:
:--) here is text with emoticon.
Anyone can help me to create these regex ?
Thanks!
Change your regex pattern to allow matches only if a certain emoticon code is not preceded or followed by non-space character:
...
$match = '#(?<!\S)(' . $quoted_emoticon .')(?!\S)#iu';
...
Related
I have a an url which looks like this https://URL.DOMAIN/blog.php?id=43&q=echo%20%27test%27.
When I use <?php echo $_GET['q'] ?> it displays echo 'test' which is what I want.
I am using this variable inside a preg_replace function which is basically made to apply a yellow background under matched strings:
preg_replace('/\b('.$_GET['q'].')\b/iu', '<span class="research-news-found">$1</span>', $news_content);
It works perfectly for "normal" strings like "apple" or whatever, but when there is a ' inside the search query it doesn't match anything.
Code example
$news_content = $news_display['news_description'];
if(isset($_GET['q'])){
$news_content = preg_replace('/\b('.$_GET['q'].')\b/iu', '<span class="research-news-found">$1</span>', $news_content);
}
$news_display['news_description'] contains the text output from DB.
Just make the pattern greedy ? and remove the trailing word boundary \b since ' is not a word character and is a word boundary:
$news_content = preg_replace('/\b('.$_GET['q'].'?)/iu',
'<span class="research-news-found">$1</span>',
$news_content);
Demo
But if you are hoping that it will actually echo test, then no. You would need to restructure your question to state what you want to achieve, not how to get this replacement to work.
I'm trying to convert text ($icon) to smiley image ($image). I used to do it with str_replace(), but that seems to perform the replace sequentially and as such it also replaces items in previously converted results (for example in the tag).
I am now using the following code:
foreach($smiliearray as $image => $icon){
$pattern[]="/(?<!\S)" . preg_quote($icon, '/') . "(?!\S)/u";
$replacement[]=" <img src='$image' border='0' alt=''> ";
}
$text = preg_replace($pattern,$replacement,$text);
This code works, but only if the smiley code is surrounded by whitespace. So basically if someone types ":);)", it won't catch it as two separate smilieys, but ":) ;)" does.
How can I fix it so that also a string of smileys (not separated by space) are converted?
Note that there can be unlimited kinds of smiley codes and smiley images. I do not know beforehand which ones, because other people can submit codes and smileys, so it is not just ":)" and ";)", but can also be "rofl", ":eh", ":-{", etc.
I can partially fix it by adding a \W non-word to the end of the 2nd capturegroup: (?!\S\W), and further by adding a 2nd $pattern and $replacement with a \W to the first capturegroup. But I don't think that is the way it should be done, and it only partially solves it.
I used to do it with str_replace(), but that seems to perform the
replace sequentially and as such it also replaces items in previously
converted results...
A good and true reason to use strtr(). You don't even need Regular Expressions:
<?php
// I assume your original array looks like this
$origSmileys = [
"/1.png" => ':)',
"/2.png" => ':(',
"/3.png" => ':P',
"/4.png" => '>:('
];
// sample input string
$str = " I'm :) but :(>:(:( now :P";
// iterating over smileys to add html tag
$newSmileys = array_map(function($value) {
return "<img src='$value' border='0' alt=''>";
}, array_flip($origSmileys));
// replace
echo strtr($str, $newSmileys);
Live demo
So i have a string and I used the strip_tags() function to remove all tags except IMG but I still have plain text next to my IMG element. Here a visual example
$myvariable = "This text needs to be removed<a href='blah_blah_blah'>Blah</a><img src='blah.jpg'>"
So using PHP strip_tags() I was able to remove all tags except the <img> tag (which is what I want). But the thing is now it didn't remove the text.
How do I remove the left over text? Text will always either before tag or after tag as well
[ADDED MORE DETAILS]
$description = 'crazy stuff<img src="https://scontent.cdninstagram.com/t51.2885-15/e15/14287934_1389514537744146_673363238_n.jpg?ig_cache_key=MTMzNzM3MzgwNjAyNDY5NDAzMA%3D%3D.2">';
that's what the variable is actually holding.
Thanks in Advance
Instead of replacing something you can very well extract the values you want:
(<(\w+).+</\2>)
To be used with preg_match(), see a demo on regex101.com.
IN PHP:
<?php
$regex = '~(<(\w+).+</\2>)~';
$string = 'crazy stuff<img src="https://scontent.cdninstagram.com/t51.2885-15/e15/14287934_1389514537744146_673363238_n.jpg?ig_cache_key=MTMzNzM3MzgwNjAyNDY5NDAzMA%3D%3D.2">here as well';
if (preg_match($regex, $string, $match)) {
echo $match[1];
}
?>
Please show your whole piece of code with the use of strip_tags.
You can try: preg_replace('~.*(<img[^>]+>)~', '$1', $myvariable);
In a PHP variable a mixed language context is present. An example is below:
$variable="This is sample text I am storing in the variable. இதன் கூடவே மற்ற மொழி எழுத்துக்களும் உள்ளன"
So the variable $variable contains both English and other language (Tamil in the above example).
Now I need to add a tag with class something enclosing the Tamil text such as:
$variable="This is sample text I am storing in the variable. <span class='tamil'>இதன் கூடவே மற்ற மொழி எழுத்துக்களும் உள்ளன</span>"
How to omit the English letters and punctuation symbols and add <span> to other language sentence completely or paragraph?
There's a unicode range that you can use to create a regex, this will help you find tamil chars in your text: http://unicode.org/charts/PDF/U0B80.pdf
[\u0B80-\u0BFA-]*
I have put together a playground for this example so that you can improve it to do what you need to do.
http://regex101.com/r/wT8hP4
The following is not gold plated code, but hope it can get you started.
<?php
$variable="This is sample text I am storing in the variable. இதன் கூடவே மற்ற மொழி எழுத்துக்களும் உள்ளன";
echo add_tamil_class($variable);
/**
* Adds a HTML Span tag around tamil text using regex
*/
function add_tamil_class($text) {
preg_match_all("/[\x{0B80}-\x{0BFA}]+/u", $text, $matches);
$tamilSentence = implode(' ', $matches[0]);
return str_replace(
$tamilSentence,
"<span class='tamil'>".$tamilSentence."</span>",
$text
);
}
As Filype mentioned, we can use the unicode ranges for this.
This should match even in cases like 'English' -> 'Tamil' -> 'English' -> 'Tamil'. Though it'll wrap extra spaces into the span.
/**
* #param String $str Input UTF-8 encoded string.
*/
function encapsulate_tamil($str)
{
return preg_replace('/[\x{0B80}-\x{0BFF}][\x{0B80}-\x{0BFF}\s]*/u',
'<span class=\'tamil\'>$0</span>', $str);
}
My current code is:
$epattern[17] = "/#(\\w+)/";
$ereplace[17] = "<a href=viewprofile.php?username=$1><font color=royalblue><b>#\\1</b></font></a>";
$postinforawb = preg_replace($epattern,$ereplace,$postinfo);
With the above code the text will highlight blue where the # symbol was used up to where a space has been entered. However I now also want it to include the "+" symbol in posts. So that the following would highlight blue: "#First+Second"
What am I needing to add to the replace?
This will do in your case:
$epattern[17] = "/#([\w\+]+)/";
But i prefer this one as you are only allowing alphabet and +:
$epattern[17] = "/#([a-zA-Z\+]+)/";
$epattern[17] = "/#([\w\+]+)/";