PHP function in array - php

My problem is that retrieveName() is not getting $1's value, but $1 is working just fine in the previous instance.
function bbcode ($string)
{
// All the default bbcode arrays.
$bbcode = array(
'#\[quote=(.*?)\](.*?)\[/quote\]#si' =>
'<span class="bbcode_quote"><b>
<a href="userprofile.php?id='.stripslashes('$1').'" target="_blank">
<span class="fake_link">'.retrieveName('$1').'</span></a> Said:</b><BR/>$2</span><BR/>'
);
$output = preg_replace(array_keys($bbcode), array_values($bbcode), $string);
$output = str_replace("\\r\\n", "<br>", $output);
return $output;
}
EDIT:
there's no strip slashes, I wish it was that simple
function retrieveName($poster_id){
$get_name = mysql_query("SELECT * FROM users WHERE userid = 'sanitizeIn($poster_id)'")
or die(mysql_error());
$name_row = mysql_fetch_array($get_name);
return $name_row['username'];
}
function sanitizeIn ($string) {
$output = mysql_real_escape_string($string);
return $output;
}

Assuming you are using preg_* functions, as you should be, you should use $1 instead of \\1. Both are valid, but $1 is the preferred syntax.
Also, you might be more interested in one of the following:
$output = preg_replace("#\[quote=(.*?)\](.*?)\[/quote\]#sie",
"'<span class=\"bbcode_quote\"><b><a href=\"userprofile.php?id='.stripslashes('$1').'\"
target=\"_blank\"><span class=\"fake_link\">'.
retrieveName(stripslashes('$1')) . '</span></a> Said:</b><BR/>$2
</span><BR/>'",$input);
Or:
$output = preg_replace_callback("#\[quote=(.*?)\](.*?)\[/quote\]#si",function($m) {
return '<span class="bbcode_quote"><b><a href="userprofile.php?id=\\1"
target="_blank"><span class="fake_link">' .
retrieveName('\\1') . '</span></a> Said:</b><BR/>\\2
</span><BR/>';
},$input);

Try this way:
$output = preg_replace_callback("#\[quote=(.*?)\](.*?)\[/quote\]#si",function($matches) {
return '<span class="bbcode_quote"><b><a href="userprofile.php?id='.stripslashes($matches[1]).'" target="_blank"><span class="fake_link">' .
retrieveName($matches[1]).'</span></a> Said:</b><BR/>'.$matches[2].'</span><BR/>';
},$input);

Related

Regex for add GET param to URL

I want to add GET parameter to all URLs in special string (like html content of a website) .
For example :
Before:
$content = '... register ... login ...';
After:
$content = '... register ... login ...';
I think that this is only done with a regular expression , for this reason I wrote this function :
function makeLinks($str)
{
$str = preg_replace('#((https?://)?([-\w]+\.[-\w\.]+)+\w(:\d+)?(/([-\w/_\.]*(\?\S+)?)?)*)#', '$1?wid=${wid}', $str);
return $str;
}
But this pattern having problems! for example :
http://google.com?foo=bar => http://google.com?wid=${wid}?foo=bar
Please help me.
Try This:
function makeLinks($str)
{
$str = preg_replace_callback('/\b((?:https?|ftp):\/\/(?:[-A-Z0-9.]+)(?:\/[-A-Z0-9+&##\/%=~_|!:,.;]*)?)(?:\?([A-Z0-9+&##\/%=~_|!:,.;]*))?/i', 'modify_url', $str);
return $str;
}
function modify_url($matches) {
$query = isset($matches[2]) ? $matches[2]:'';
$result = $matches[1].'?'.$query;
if(!empty($query)) $result .= '&';
return $result.'wid=${wid}';
}
Optionally you can just add # without affecting the ending result. I hate to use them, but here it is in case you want to use them:
function modify_url($matches) {
$result = $matches[1].'?'.#$matches[2];
if(!#empty($matches[2])) $result .= '&';
return $result.'wid=${wid}';
}
Idealy, you should extract the urls and parse them, but this solution should work.
I think there may be a short way. My solution :
function makeLinks($str) {
preg_match_all('|(https?:\/\/(www\.)?[-a-zA-Z0-9#:%._\+~#=]{2,256}\.[a-z]{2,6}\b([-a-zA-Z0-9#:%_\+.~#?&//=]*))|', $str, $urls);
if ($urls && isset($urls[1])) {
foreach ($urls[1] as $url) {
$new_url = $url . (strpos($url, '?') ? '&' : '?') . 'wid=${wid}';
$str = str_replace($url, $new_url, $str);
}
}
return $str;
}

Regex: Modify img src tags

I try to replace all images in a html document with inline image (data:image).
I've a sample code which does not work:
function data_uri($filename) {
$mime = mime_content_type($filename);
$data = base64_encode(file_get_contents($filename));
return "data:$mime;base64,$data";
}
function img_handler($matches) {
$image_element = $matches[1];
$pattern = '/(src=["\'])([^"\']+)(["\'])/';
$image_element = preg_replace($pattern, create_function(
$matches,
$matches[1] . data_uri($matches[2]) . $matches[3]),
$image_element);
return $image_element;
}
$content = (many) different img tags
$search = '(<img\s+[^>]+>)';
$content = preg_replace_callback($search, 'img_handler', $content);
Could somebody check this code? Thanks!
UPDATE:
(...) Warning file_get_contents() [function.file-get-contents]: Filename cannot be empty (...)
That means the src url is not in the handler :(
UPDATE 2
<?php
function data_uri($filename) {
$mime = mime_content_type($filename);
$data = base64_encode(file_get_contents($filename));
return "data:$mime;base64,$data";
}
function img_handler($matches) {
$image_element = $matches[0];
$pattern = '/(src=["\'])([^"\']+)(["\'])/';
$image_element = preg_replace_callback($pattern, create_function(
$matchess,
$matchess[1] . data_uri($matchess[2]) . $matchess[3]),
$image_element);
return $image_element;
}
$content = '<img class="alignnone" src="http://upload.wikimedia.org/wikipedia/commons/thumb/4/44/Googlelogoi.png/180px-Googlelogoi.png" alt="google" width="580" height="326" title="google" />';
$search = '(<img\s+[^>]+>)';
$content = preg_replace_callback($search, 'img_handler', $content);
echo $content;
?>
I've upload this test file -> http://goo.gl/vWl9B
Your regex is alright. You are using create_function() wrong. And subsequently the inner preg_replace_callback() doesn't work. The call to data_uri() happens before any regex-replacement takes place, hencewhy the undefined filename error.
Use a proper callback function:
$image_element = preg_replace_callback($pattern, "data_uri_callback", $image_element);
Then move your code into there:
function data_uri_callback($matchess) {
return $matchess[1] . data_uri($matchess[2]) . $matchess[3];
}

How i do capture just links with this regex?

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;
}

Problem returning excerpt with specified number of characters

I'm using the following code to grab a string and return a spesific number of characters
<div class="top_posts">
<ul>';
}
elseif($i>1 && $i<=$number_of_posts)
{
$retour.= "\n" . '<li>';
if($image_url) { $retour .= '<img src="' . get_bloginfo('template_directory') . '/js/timthumb.php?src=' . $image_url . '&h=120&w=180&zc=1" alt="" />'; }
$retour .= '<h6>' . the_title("","",false) . '</h6>';
$retour.= get_wpe_excerpt('wpe_popular_posts');
$retour.='</li>';
if($i%2==1)
$retour.= "\n" . '<li class="clear">&</li>';
}
$i++;
endforeach;
$retour.='</ul></div>';
return $retour;
}
add_shortcode('popular-posts', 'popular_posts_code');
The chunk at issue is this part
$retour.= get_wpe_excerpt('wpe_popular_posts');
which calls to
function wpe_popular_posts($length) {
return 55;
}
However I'm still getting the full text string untrimmed - any help appreciated.
//update
The get_wpe_excerpt function looks like this
function get_wpe_excerpt($length_callback='', $more_callback='') {
if(function_exists($length_callback)){
add_filter('excerpt_length', $length_callback);
}
if(function_exists($more_callback)){
add_filter('excerpt_more', $more_callback);
}
$output = get_the_excerpt();
$output = apply_filters('wptexturize', $output);
$output = apply_filters('convert_chars', $output);
$output = '<p>'.$output.'</p>';
return $output;
}
Now sure how the get_wpe_excerpt() function is done. You may want to try the simple code I used in several WordPress themes.
implode(' ', array_slice(explode(' ', get_the_content()), 0, 55));
You want to return the first 55 characters of the string?
Try substr($input, 0, 55);
However I really don't understand what's going on with that call to $retour.= get_wpe_excerpt('wpe_popular_posts');... so maybe I am misunderstanding what you are trying to achieve?

is there a PHP library that handles URL parameters adding, removing, or replacing?

when we add a param to the URL
$redirectURL = $printPageURL . "?mode=1";
it works if $printPageURL is "http://www.somesite.com/print.php", but if $printPageURL is changed in the global file to "http://www.somesite.com/print.php?newUser=1", then the URL becomes badly formed. If the project has 300 files and there are 30 files that append param this way, we need to change all 30 files.
the same if we append using "&mode=1" and $printPageURL changes from "http://www.somesite.com/print.php?new=1" to "http://www.somesite.com/print.php", then the URL is also badly formed.
is there a library in PHP that will automatically handle the "?" and "&", and even checks that existing param exists already and removed that one because it will be replaced by the later one and it is not good if the URL keeps on growing longer?
Update: of the several helpful answers, there seems to be no pre-existing function addParam($url, $newParam) so that we don't need to write it?
Use a combination of parse_url() to explode the URL, parse_str() to explode the query string and http_build_query() to rebuild the querystring. After that you can rebuild the whole url from its original fragments you get from parse_url() and the new query string you built with http_build_query(). As the querystring gets exploded into an associative array (key-value-pairs) modifying the query is as easy as modifying an array in PHP.
EDIT
$query = parse_url('http://www.somesite.com/print.php?mode=1&newUser=1', PHP_URL_QUERY);
// $query = "mode=1&newUser=1"
$params = array();
parse_str($query, $params);
/*
* $params = array(
* 'mode' => '1'
* 'newUser' => '1'
* )
*/
unset($params['newUser']);
$params['mode'] = 2;
$params['done'] = 1;
$query = http_build_query($params);
// $query = "mode=2&done=1"
Use this:
http://hu.php.net/manual/en/function.http-build-query.php
http://www.addedbytes.com/php/querystring-functions/
is a good place to start
EDIT: There's also http://www.php.net/manual/en/class.httpquerystring.php
for example:
$http = new HttpQueryString();
$http->set(array('page' => 1, 'sort' => 'asc'));
$url = "yourfile.php" . $http->toString();
None of these solutions work when the url is of the form:
xyz.co.uk?param1=2&replace_this_param=2
param1 gets dropped all the time
.. which means it never works EVER!
If you look at the code given above:
function addParam($url, $s) {
return adjustParam($url, $s);
}
function delParam($url, $s) {
return adjustParam($url, $s);
}
These functions are IDENTICAL - so how can one add and one delete?!
using WishCow and sgehrig's suggestion, here is a test:
(assuming no anchor for the URL)
<?php
echo "<pre>\n";
function adjustParam($url, $s) {
if (preg_match('/(.*?)\?/', $url, $matches)) $urlWithoutParams = $matches[1];
else $urlWithoutParams = $url;
parse_str(parse_url($url, PHP_URL_QUERY), $params);
if (strpos($s, '=') !== false) {
list($var, $value) = split('=', $s);
$params[$var] = urldecode($value);
return $urlWithoutParams . '?' . http_build_query($params);
} else {
unset($params[$s]);
$newQueryString = http_build_query($params);
if ($newQueryString) return $urlWithoutParams . '?' . $newQueryString;
else return $urlWithoutParams;
}
}
function addParam($url, $s) {
return adjustParam($url, $s);
}
function delParam($url, $s) {
return adjustParam($url, $s);
}
echo "trying add:\n";
echo addParam("http://www.somesite.com/print.php", "mode=3"), "\n";
echo addParam("http://www.somesite.com/print.php?", "mode=3"), "\n";
echo addParam("http://www.somesite.com/print.php?newUser=1", "mode=3"), "\n";
echo addParam("http://www.somesite.com/print.php?newUser=1&fee=0", "mode=3"), "\n";
echo addParam("http://www.somesite.com/print.php?newUser=1&fee=0&", "mode=3"), "\n";
echo addParam("http://www.somesite.com/print.php?mode=1", "mode=3"), "\n";
echo "\n", "now trying delete:\n";
echo delParam("http://www.somesite.com/print.php?mode=1", "mode"), "\n";
echo delParam("http://www.somesite.com/print.php?mode=1&newUser=1", "mode"), "\n";
echo delParam("http://www.somesite.com/print.php?mode=1&newUser=1", "newUser"), "\n";
?>
and the output is:
trying add:
http://www.somesite.com/print.php?mode=3
http://www.somesite.com/print.php?mode=3
http://www.somesite.com/print.php?newUser=1&mode=3
http://www.somesite.com/print.php?newUser=1&fee=0&mode=3
http://www.somesite.com/print.php?newUser=1&fee=0&mode=3
http://www.somesite.com/print.php?mode=3
now trying delete:
http://www.somesite.com/print.php
http://www.somesite.com/print.php?newUser=1
http://www.somesite.com/print.php?mode=1
You can try this:
function removeParamFromUrl($query, $paramToRemove)
{
$params = parse_url($query);
if(isset($params['query']))
{
$queryParams = array();
parse_str($params['query'], $queryParams);
if(isset($queryParams[$paramToRemove])) unset($queryParams[$paramToRemove]);
$params['query'] = http_build_query($queryParams);
}
$ret = $params['scheme'].'://'.$params['host'].$params['path'];
if(isset($params['query']) && $params['query'] != '' ) $ret .= '?'.$params['query'];
return $ret;
}

Categories