This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Replace a list of emoticons with their images
i'm developing a website where i want to give users possibility to put smiles on posts.
My (just functional) idea is to use array in this way:
$emoticons = array(
array("17.gif",":)"),
array("6.jpg",":P"),
.....
array("9.jpg",":'("),
array("5.gif","X)")
);
with image on [0] and emoticon on [1].
And on each $post:
foreach($emoticons as $emoticon){
$quoted_emoticon = preg_quote($emoticon[1],"#");
$match = '#(?!<\w)(' . $quoted_emoticon .')(?!\w)#';
$post = preg_replace($match,'<img src="images/emoticons/'.$emoticon[0].'">',$post);
}
This is working good, but my problem is '#(?!<\w)(' and ')(?!\w)#' because I want emoticons to apply only when preceding characters are "begin" (^) or "blank" and succeeding characters are "end" ($) or "blank". What is the right regex to do this?
I think you want the positive look behind and positive look ahead.
Example:
(?<=\s|^)(\:\))(?=\s|$)
Your example updated:
foreach($emoticons as $emoticon){
$quoted_emoticon = preg_quote($emoticon[1],"#");
$match = '(?<=\s|^)(' . $quoted_emoticon .')(?=\s|$)';
$post = preg_replace($match,'<img src="images/emoticons/'.$emoticon[0].'">',$post);
}
I would go with:
$e = array( ':)' => '1.gif',
':(' => '2.gif',
);
foreach ($e as $sign => $file) {
$sign = preg_replace('/(.)/', "\\$1", $sign);
$pattern = "/(?<=\s|^)$sign(?=\s|$)/";
$post = preg_replace($pattern, " <img src=\"images/emoticons/$file\">", $post);
}
Related
This question already has answers here:
How to remove the querystring and get only the URL?
(16 answers)
Closed 2 years ago.
I would like to remove anything that follows after a specific set of characters (i.e. filetypes / extensions). I have tried numerous scripts I found online, but none really manage to do what I need, they either remove the file extension as well, or keep parts of the arguments that follow.
$urls = array(
'http://www.example.com/images/image1.jpg',
'http://www.example.com/images/image2.png?arg=value',
'http://www.example.com/images/image3.jpg?foo=bar',
'http://www.example.com/images/image4.gif?v=1',
'http://www.example.com/images/image5.bmp?x=y',
'http://www.example.com/images/image6.tiff?werdfs=234234'
);
Desired outcome:
http://www.example.com/images/image1.jpg
http://www.example.com/images/image2.png
http://www.example.com/images/image3.jpg
http://www.example.com/images/image4.gif
http://www.example.com/images/image5.bmp
http://www.example.com/images/image6.tiff
Maybe this one help you.
$re = '/^.*(?:\.)[a-zA-Z]+/m';
$urls = array(
'http://www.example.com/images/image1.jpg',
'http://www.example.com/images/image2.png?arg=value',
'http://www.example.com/images/image3.jpg?foo=bar',
'http://www.example.com/images/image4.gif?v=1',
'http://www.example.com/images/image5.bmp?x=y',
'http://www.example.com/images/image6.tiff?werdfs=234234',
'asdasd'
);
foreach ($urls as $url) {
preg_match($re, $url, $matches);
if ($matches) {
echo $matches[0];
echo "\n";
}
}
Output
http://www.example.com/images/image1.jpg
http://www.example.com/images/image2.png
http://www.example.com/images/image3.jpg
http://www.example.com/images/image4.gif
http://www.example.com/images/image5.bmp
http://www.example.com/images/image6.tiff
How about PHP's parse_url() and basename?
$inName = $urls[0]; // for example
$newName = parse_url($inName,PHP_URL_SCHEME)
. parse_url($inName,PHP_URL_HOST)
. parse_url($inName,PHP_URL_PATH)
. basename($inName);
This question already has answers here:
Parse through a string php and replace substrings
(2 answers)
Closed 9 years ago.
OK, that's what I need :
Get all entries formatted like %%something%%, as given by the regex /%%([A-Za-z0-9\-]+)%%/i
Replace all instances with values from a table, given the index something.
E.g.
Replace %%something%% with $mytable['something'], etc.
If it was a regular replacement, I would definitely go for preg_replace, or even create an array of possible replacements... But what if I want to make it a bit more flexible...
Ideally, I'd want something like preg_replace($regex, $mytable["$1"], $str);, but obviously it doesn't look ok...
How should I go about this?
Code:
<?php
$myTable = array(
'one' => '1!',
'two' => '2!',
);
$str = '%%one%% %%two%% %%three%%';
$str = preg_replace_callback(
'#%%(.*?)%%#',
function ($matches) use ($myTable) {
if (isset($myTable[$matches[1]]))
return $myTable[$matches[1]];
else
return $matches[0];
},
$str
);
echo $str;
Result:
1! 2! %%three%%
if you don't want to tell upper from lower,
<?php
$myTable = array(
'onE' => '1!',
'Two' => '2!',
);
$str = '%%oNe%% %%twO%% %%three%%';
$str = preg_replace_callback(
'#%%(.*?)%%#',
function ($matches) use ($myTable) {
$flipped = array_flip($myTable);
foreach ($flipped as $v => $k) {
if (!strcasecmp($k, $matches[1]))
return $v;
}
return $matches[1];
},
$str
);
echo $str;
This question already has answers here:
Unknown modifier '/' in ...? what is it? [duplicate]
(4 answers)
Closed 9 years ago.
I'm trying to use an array of regular expressions to find and replace within a string in PHP, however I'm getting the error unknown modifier. I'm aware this appears to be a popular issue, however I don't understand how to fix it in my scenario.
Here is my original regex pattern:
{youtube((?!}).)*}
I run the following code against it to escape any characters:
$pattern = '/' . preg_quote($pattern) . '/';
That returns the following:
/\{youtube\(\(\?\!\}\)\.\)\*\}/
However, when I run this pattern through preg_replace I get the following error:
Warning: preg_replace() [function.preg-replace]: Unknown modifier 'y' ...
Any idea what needs to be changed, and at what stage of the code I've show here?
Many thanks
Edit 1
As requested, here is the code I'm using:
$content = "{youtube}omg{/youtube}";
$find = array();
$replace = array();
$find[] = '{youtube((?!}).)*}';
$replace[] = '[embed]http://www.youtube.com/watch?v=';
$find[] = '{/youtube((?!}).)*}';
$replace[] = '[/embed]';
foreach ( $find as $key => $value ) {
$find[$key] = '/' . preg_quote($value) . '/';
}
echo preg_replace($find, $replace, $content);
Here's a live example
You should pass delimiter as second parameter for preg_quote like this:
$find[$key] = '/' . preg_quote ($value, '/') . '/';
Otherwise, delimiter will not be quoted and thus will cause problems.
Simply change your Regex delimiter to something that's not used in the pattern, in this example I used # which works fine.
preg_quote only escapes . \ + * ? [ ^ ] $ ( ) { } = ! < > | : -, so when using a non-escaped character in your pattern, but also as your regex delimiter, it's not going to work as expected. Either change the delimiter as above, or pass it into preg_quote explicitely as part of the preg_quote($str, $delimiter) overload.
$content = "{youtube}omg{/youtube}";
$find = array();
$replace = array();
$find[] = '{youtube((?!}).)*}';
$replace[] = '[embed]http://www.youtube.com/watch?v=';
$find[] = '{/youtube((?!}).)*}';
$replace[] = '[/embed]';
foreach ( $find as $key => $value ) {
$find[$key] = '#' . preg_quote($value) . '#';
}
echo preg_replace($find, $replace, $content);
I may be sat in a hospital waiting room away from a computer, but what you're doing seems to have way over complicated the problem.
If I am to understand this correctly, you want to replace some like this:
{youtube something="maybe"}http://...{/youtube}
With:
[embed]http://...[/embed]
No?
If that's the case the solution is as simple as something along the lines of:
preg_replace('#{(/?)youtube[^}]*}#', '[\1embed]', $content);
The important considerations being the preservation of the open/closed-ness of the tags, and wrapping the regex in something that doesn't conflict quite so much with your target string, in this case, hashes.
I have a question that can I replace a certain character like # with # in a string.
I have all the character checkers and their replacer in an array. Like this--
$string_check = array(
"#" => "#",
.... and so on (list is too big)
);
So how can I do this thing. Please help me out. I only have 20 days of experience with php.
You can feed your translation table right into strtr():
$table = array(
'#' => '...',
);
$result = strtr($source, $table);
str_replace does exactly that and it also accepts arrays as replacement maps:
$string_check = array(
"#" => "#"
);
$result = str_replace (array_keys($string_check), array_values($string_check), $original);
$search = array('hello','foo');
$replace = array('world','bar');
$text = 'hello foo';
$result = str_replace($search,$replace,$text);
// $result will be 'world bar'
but in your case it looks like some kind of encoding, have you tried the htmlspecialchars?
I'm modifying PHP Markdown (a PHP parser of the markup language which is used here on Stack Overflow) trying to implement points 1, 2 and 3 described by Jeff in this blog post. I've easily done the last two, but this one is proving very difficult:
Removed support for intra-word
emphasis like_this_example
In fact, in the "normal" markdown implementation like_this_example would be rendered as likethisexample. This is very undesirable; I want only _example_ to become example.
I looked in the source code and found the regex used to do the emphasis:
var $em_relist = array(
'' => '(?:(?<!\*)\*(?!\*)|(?<!_)_(?!_))(?=\S|$)(?![.,:;]\s)',
'*' => '(?<=\S|^)(?<!\*)\*(?!\*)',
'_' => '(?<=\S|^)(?<!_)_(?!_)',
);
var $strong_relist = array(
'' => '(?:(?<!\*)\*\*(?!\*)|(?<!_)__(?!_))(?=\S|$)(?![.,:;]\s)',
'**' => '(?<=\S|^)(?<!\*)\*\*(?!\*)',
'__' => '(?<=\S|^)(?<!_)__(?!_)',
);
var $em_strong_relist = array(
'' => '(?:(?<!\*)\*\*\*(?!\*)|(?<!_)___(?!_))(?=\S|$)(?![.,:;]\s)',
'***' => '(?<=\S|^)(?<!\*)\*\*\*(?!\*)',
'___' => '(?<=\S|^)(?<!_)___(?!_)',
);
I tried to open it in Regex Buddy but it wasn't enough, and after spending half an hour working on it I still don't know where to start. Any suggestions?
Some people, when confronted with a
problem, think "I know, I'll use
regular expressions." Now they have
two problems.
I use RegexBuddy too. :)
You may want to try the following code:
<?php
$line1 = "like_this_example";
$line2 = "I want only _example_ to become example";
$pattern = '/\b_(?P<word>.*?)_\b/si';
if (preg_match($pattern, $line1, $matches))
{
$result = $matches['word'];
var_dump($result);
}
if (preg_match($pattern, $line2, $matches))
{
$result = $matches['word'];
var_dump($result);
}
?>
I was able to grab only individual _enclosed_ words via:
$input = 'test of _this_ vs stuff_like_this...and here is _anothermatch_ and_another_fake_string';
$pattern = '#(?<=\s|^)(?<!_)(_[^_]*_)(?!_)#is';
preg_match_all($pattern, $input, $matches);
print_r($matches);
I'm not sure how exactly that would fit into the above code though. You would probably need to pair it with the other patterns below to account for the two and three match situations:
$pattern = '#(?<=\s|^)(?<!_)(__[^_]*__)(?!_)#is';
$pattern = '#(?<=\s|^)(?<!_)(___[^_]*___)(?!_)#is';