I recenlythave tried to convert the preg_replace() line to preg_replace_callback, but with no success. I did try the methods on Stackoverflow, but they seem to be different.
Hope I could get some help with it.
function ame_process_bbcode(&$parser, &$param1, $param2 = '')
{
if (class_exists('vB_BbCodeParser_Wysiwyg') AND is_a($parser, 'vB_BbCodeParser_Wysiwyg'))
{
return $text;
}
else
{
global $vbulletin;
($hook = vBulletinHook::fetch_hook('automediaembed_parse_bbcode_start')) ? eval($hook) : false;
$ameinfo = fetch_full_ameinfo();
$text = preg_replace($ameinfo['find'], $ameinfo['replace'], ($param2 ? $param2 : $param1), 1);
($hook = vBulletinHook::fetch_hook('automediaembed_parse_bbcode_end')) ? eval($hook) : false;
return $text;
}
}
Updates: Thanks to #Barmar, I know now that the issue is related to the fetch_full_ameinfo function.. I will add function below. Maybe it will help others in the long run. I will also include the fix whenever I am done. Thanks to #Barmar for the help.
function &fetch_full_ameinfo($findonly = false, $refresh = false)
{
global $db, $vbulletin, $vbphrase, $stylevar;
static $ameinfo = array();
static $inied, $lastfind;
if ($refresh)
{
$inied = false;
}
if ($lastfind && !$findonly)
{
$inied = false;
$ameinfo = array();
}
if (!$inied)
{
if (!$refresh AND $vbulletin->options['automediaembed_cache'])
{
$path = $vbulletin->options['automediaembed_cache_path'];
if (file_exists($path . "findonly.php"));
{
if ($findonly)
{
include($path . "findonly.php");
}
else
{
include($path . "ameinfo.php");
}
$inied = true;
$lastfind = $findonly;
return $ameinfo;
}
}
if ($vbulletin->options['automediaembed_resolve'])
{
$embed = ",IF(extraction=1 AND embedregexp!= '', embedregexp, '') as embedregexp, IF(extraction=1 AND validation!= '', validation, '') as validation";
$embedwhere = " AND ((extraction = 0 AND embedregexp = '') OR (extraction = 1)) ";
}
else
{
$embedwhere = " AND embedregexp = ''";
}
$sql = "SELECT findcode" . (!$findonly ? ", replacecode,title,container,ameid" : ",extraction$embed") . " FROM " . TABLE_PREFIX . "automediaembed WHERE status=1 $embedwhere
ORDER BY displayorder, title ASC";
$results = $db->query_read_slave($sql);
while ($result = $db->fetch_array($results))
{
if ($result['findcode'])
{
if (!$findonly)
{
$ameinfo['find'][] = "~($result[findcode])~ie";
$ameinfo['replace'][] = 'ame_match_bbcode($param1, $param2, \'' . $result['ameid'] . '\', \'' . ame_slasher($result['title']) . '\', ' . $result['container'] . ', \'' . ame_slasher($result['replacecode']) . '\', \'\\1\', \'\\2\', \'\\3\', \'\\4\', \'\\5\', \'\\6\')';
}
else
{
$ameinfo['find'][] = "~(\[url\]$result[findcode]\[/url\])~ie";
$ameinfo['find'][] = "~(\[url=\"?$result[findcode]\"?\](.*?)\[/url\])~ie";
$ameinfo['replace'][] = 'ame_match("\1", "", ' . intval($result['extraction']) .', "' . ($result['embedregexp'] ? "~" . ame_slasher($result['embedregexp']) . "~sim" : "") . '", "' . ($result['validation'] ? "~" . ame_slasher($result['validation']) . "~sim" : "") . '",$ameinfo)';
$ameinfo['replace'][] = 'ame_match("\1", "\2", ' . intval($result['extraction']) .', "' . ($result['embedregexp'] ? "~" . ame_slasher($result['embedregexp']) . "~sim" : "") . '", "' . ($result['validation'] ? "~" . ame_slasher($result['validation']) . "~sim" : "") . '", $ameinfo)';
}
}
}
$inied = true;
}
$lastfind = $findonly;
return $ameinfo;
}
You can't put the replacement function in fetch_full_ameinfo(), because it needs to refer to the $param1 and $param2 variables, which are local to this function.
This means it needs to use eval() in the current function (this is essentially what preg_replace() does internally when it processes the /e flag).
You need to change the replacement string that fetch_full_ameinfo() creates so that it uses a variable instead of \1, \2, etc. to refer to the capture groups, because the callback function receives the captured matches as an array. So replace the block beginning with if (!$findonly) with this:
if (!$findonly)
{
$ameinfo['find'][] = "~($result[findcode])~i";
$ameinfo['replace'][] = 'ame_match_bbcode($param1, $param2, \'' . $result['ameid'] . '\', \'' . ame_slasher($result['title']) . '\', ' . $result['container'] . ', \'' . ame_slasher($result['replacecode']) . '\', \'$match[1]\', \'$match[2]\', \'$match[3]\', \'$match[4]\', \'$match[5]\', \'$match[6]\')';
}
else
{
$ameinfo['find'][] = "~(\[url\]$result[findcode]\[/url\])~i";
$ameinfo['find'][] = "~(\[url=\"?$result[findcode]\"?\](.*?)\[/url\])~i";
$ameinfo['replace'][] = 'ame_match("$match[1]", "", ' . intval($result['extraction']) .', "' . ($result['embedregexp'] ? "~" . ame_slasher($result['embedregexp']) . "~sim" : "") . '", "' . ($result['validation'] ? "~" . ame_slasher($result['validation']) . "~sim" : "") . '",$ameinfo)';
$ameinfo['replace'][] = 'ame_match("$match[1]", "$match[2]", ' . intval($result['extraction']) .', "' . ($result['embedregexp'] ? "~" . ame_slasher($result['embedregexp']) . "~sim" : "") . '", "' . ($result['validation'] ? "~" . ame_slasher($result['validation']) . "~sim" : "") . '", $ameinfo)';
}
Then change your code to:
$text = preg_replace_callback($ameinfo['find'], function($match) use (&$param1, &$param2, &$ameinfo) {
return eval($ameinfo['replace']);
}, ($param2 ? $param2 : $param1), 1);
Recently I was asked to write my own implementation of PHP serialize(), unserialize() functions. My functions should return identical results as original PHP internal functions.
I made some progress with serialize() function :
<?php
function serializator($input)
{
$args = count(func_get_args());
if ( $args > 1) { throw new Exception("Serializator function requires exactly 1 parameter. {$args} given"); };
switch ($input) :
case is_array($input) :
$length = count($input);
$str = gettype($input)[0] . ':' . $length . ':{';
foreach ($input as $key => $value):
if (is_array($value)) {
$str .= gettype($key)[0] . ':' ;
$str .= !is_int($key) ? strlen($key) . ':' . '"' . $key . '"' . ';' : $key . ';';
$str .= serializator($value);
}
else {
$str .= gettype($key)[0] . ':' ;
$str .= !is_int($key) ? strlen($key) . ':' . '"' . $key . '"' . ';' : $key . ';';
$str .= gettype($value)[0] . ':' ;
$str .= !is_int($value) ? strlen($value) . ':' . '"' . $value . '"' . ";" : $value . ';';
}
endforeach;
$str .= '}';
break;
case is_object( $input ) :
$str = ucfirst(gettype($input)[0]) . ':' . strlen(get_class($input)) . ':' . '"' . get_class($input) . '"';
$str .= substr(serializator((array)$input), 1);
break;
case is_int( $input) || is_bool($input) || is_null($input) :
$str = gettype($input)[0] . ':' . $input;
break;
case is_string( $input) :
$str = gettype($input)[0] . ':' . strlen($input). ':' . '"' . $input . '"';
break;
case is_float($input) :
$precision = ini_get('serialize_precision');
$str = gettype($input)[0] . ':' . $input;
break;
case is_resource($input):
$str = 'i:0'; // resource is not serializable
break;
default:
return false;
endswitch;
return $str;
}
But struggling with unserialize() implementation. Could anyone point out from where to start thinking or looking? :) Thanks.
So I I've tried to make this code log an exception but it gives me the error message object of class domain_model could not be converted to string
The function looks as follows:
function errorLog($log, $error_type, $string, $file, $row, $error_hash, $error_trace)
{
$text = $error_hash . ' (' . date('Y-m-d H:i') . "):\n[Error type]: " . $error_type . "\n[Message]: " . $string . "\n[File]: " . $file . "\n[Row]: " . $row . "\n";
$text .= "[Trace]:\n";
foreach ($error_trace as $t)
{
$text .= ((isset($t['type']) && isset($t['object'])) ? $t['object'] . $t['type'] . $t['function'] : $t['function']) . "\n";
$text .= $t['file'] . "\n";
$text .= $t['line'] . "\n";
$text .= print_r($t['file'], 1) . "\n";
}
file_put_contents(BASE . $log . '.log', $text, FILE_APPEND);
}
After alot of thinking eventually saw that the line in making a mess is infact this one:
$text .= ((isset($t['type']) && isset($t['object'])) ? $t['object'] . $t['type'] . $t['function'] : $t['function']) . "\n";
And as I see it the only one in need of conversion should be $t['object'] however using (string)$t['object'] didn't work and still gives me the same error. Is there any other solution on how to convert it to a string than this?
I've looked at how they suggest it to be done here
This question already has answers here:
How can I convert ereg expressions to preg in PHP?
(4 answers)
Closed 9 years ago.
I Just Bought a PHP Script That Was Working Properly Till I Test It ON my Web Server.
When I ran THe Script It looks Great But When I click the Sub-Category of my Website I gives me This Error
"Deprecated: Function ereg_replace() is deprecated in /home/*/public_html/includes/functions.php on line 61"
My Script is Look LIke This:
<?php function generate_link($pagename,$c='',$k='',$q='',$p='',$ktext=''){
if (USE_SEO_URLS==true){
switch ($pagename){
case 'category.php':
$result ='c' . $c . '.html';
break;
case 'questions.php':
$result ='q-c' . $c . '-k' . $k . '-p' . $p . '-' . str_replace(" ","-",$ktext) . '.html';
break;
case 'answer.php':
$result ='a' . $q . '-c' . $c . '-k' . $k . '.html';
break;
}
}
else {
switch ($pagename){
case 'category.php':
$result ='category.php?c=' . $c;
break;
case 'questions.php':
$result ='questions.php?c=' . $c . '&k=' . $k . '&p=' . $p . '&ktext=' . str_replace(" ","-",$ktext) ;
break;
case 'answer.php':
$result ='answer.php?k=' . $k . '&c=' . $c . '&id=' . $q ;
break;
}
}
return $result; } function db_prepare_input($string) {
if (is_string($string)) {
return trim(sanitize_string(stripslashes($string)));
} elseif (is_array($string)) {
reset($string);
while (list($key, $value) = each($string)) {
$string[$key] = db_prepare_input($value);
}
return $string;
} else {
return $string;
} } function sanitize_string($string) {
$string = ereg_replace(' +', ' ', trim($string));
return preg_replace("/[<>]/", '_', $string);}?>
Sorry , My Code Is also Not Proper Formatted. I face Great Problem When I post this Question Stackoverflow. Any Help Is appreciated. The Error Is Occur in Line 61. I am New in PHP. I check, There is ereg and preg Both Functions are present. please help me..
Thanks
ereg_replace deprecated. Use preg_replace like this:
$string = preg_replace('/ \+/', ' ', trim($string));
That is important / \+/ pattern. Space and plus(+)
For my Zend Framework library i have this view-helper that indents code.
I have added the solution in the code below
<?php
class My_View_Helper_Indent
{
function indent($indent, $string, $space = ' ')
{
if($string == '') {
return '';
}
$indent = str_repeat($space, $indent);
$content = $indent . str_replace("\n", "\n" . $indent, rtrim($string)) . PHP_EOL;
// BEGIN SOLUTION TO PROBLEM
// Based on user CodeAngry's answer
$callback = function($matches) use ($indent) {
$matches[2] = str_replace("\n" . $indent, "\n", $matches[2]);
return '<textarea' . $matches[1] . '>' . $matches[2] . '</textarea>';
};
$content = preg_replace_callback('~<textarea(.*?)>(.*?)</textarea>~si', $callback, $content);
// END
return $content;
}
}
And with the following test code..
$content = 'This is some text' . PHP_EOL;
$content .= '<div>' . PHP_EOL;
$content .= ' Text inside div, indented' . PHP_EOL;
$content .= '</div>' . PHP_EOL;
$content .= '<form>' . PHP_EOL;
$content .= ' <ul>' . PHP_EOL;
$content .= ' <li>' . PHP_EOL;
$content .= ' <label>inputfield</label>' . PHP_EOL;
$content .= ' <input type="text" />' . PHP_EOL;
$content .= ' </li>' . PHP_EOL;
$content .= ' <li>' . PHP_EOL;
$content .= ' <textarea cols="80" rows="10">' . PHP_EOL;
$content .= 'content of text area' . PHP_EOL;
$content .= ' this line is intentionally indented with 3 whitespaces' . PHP_EOL;
$content .= 'content of text area' . PHP_EOL;
$content .= ' </textarea>' . PHP_EOL;
$content .= ' </li>' . PHP_EOL;
$content .= ' </ul>' . PHP_EOL;
$content .= '</form>' . PHP_EOL;
$content .= 'The end';
echo $this->view->indent (6, $content);
What i would like to do, is to remove X whitespace characters from lines with the textarea tags. Where X matches the number of spaces that the code was indented, in the example above it's 6 spaces.
$html = preg_replace('~<textarea(.*?)>\s*(.*?)\s*</textarea>~si',
'<textarea$1>$2</textarea>', $html);
Try this regular expression. Should trim the contents of your textarea contents. Is this what you need?
OR:
$html = preg_replace_callback('~<textarea(.*?)>(.*?)</textarea>~si', function($matches){
$matches[2] = trim($matches[2]); // trim 2nd capture (inner textarea)
return "<textarea{$matches[1]}>{$matches[2]}</textarea>";
}, $html);