php - deprecated function ereg_replace() is deprecated in php [duplicate] - php

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(+)

Related

Adding custom masks to phone numbers

So i'm creating a simple function to mask phone numbers. My phone numbers have a 9 digits and i want preg_replace them with a given mask like 2-2-2-1-2 or 3-2-2-2 and etc.
I tried this:
$mask = explode('-', '3-2-2-2');
$pattern = '';
$replace = '';
foreach ($mask as $key => $value) {
if ($key == 0) {
$pattern = '/\(?(\d{' . $value . '})\)?[- ]';
$replace = '$' . ++$key . '-';
continue;
}
if ($key == count($mask) - 1) {
$pattern .= '?(\d{' . $value . '})/';
$replace .= '$' . ++$key;
break;
}
$pattern .= '?(\d{' . $value . '})[- ]';
$replace .= '$' . ++$key . '-';
}
return preg_replace($pattern, $replace, '902000810');
and the result is 902-00-08-10. Sometimes getting error preg_replace(): No ending delimiter '/' found. How can i refactor this to not getting errors?
Assuming:
$num = '902000810';
$mask = explode('-', '3-2-2-2');
There're other ways than using regex to format a phone number from the mask.
using formatted strings:
$maskPH = array_map(fn($i) => "%{$i}s", $mask);
$formatI = implode('', $maskPH);
$formatO = implode('-', $maskPH);
$result = vsprintf($formatO, sscanf($num, $formatI));
using unpack:
$format = array_reduce($mask, function ($c, $i) {
static $j = 0;
return "{$c}A{$i}_" . $j++ . "/";
});
$result = implode('-', unpack($format, $num));
preg_replace(): No ending delimiter '/' found
means that your pattern does not terminate with a / as last character.
But all three patterns lack proper formatting:
You should modify them accordingly.
From:
$pattern = '/\(?(\d{' . $value . '})\)?[- ]';
$pattern .= '?(\d{' . $value . '})/';
$pattern .= '?(\d{' . $value . '})[- ]';
To:
$pattern = '/\(?(\d{' . $value . '})\)?[- ]/';
$pattern .= '/?(\d{' . $value . '})/';
$pattern .= '/?(\d{' . $value . '})[- ]/';

php domain validation

I need bit help as I am facing two issues.
Links without domain extension (.com, .net, ect) will be stored in
database as single words
Script allows for self shortening the shortner url which is a major
issue.
How can I
Check for domain extension else fail submit
and
Check if user is trying to shorten my own link and fail as well.
My code:
function remove_http($url)
{
$disallowed = array('http://', 'https://', 'http//', 'https//');
foreach($disallowed as $d) {
if(strpos($url, $d) === 0) {
return str_replace($d, '', $url);
}
}
return $url;
}
$url_to_shorten = get_magic_quotes_gpc() ? stripslashes(trim($_REQUEST['url'])) : trim($_REQUEST['url']);
if(!empty($url_to_shorten) || parse_url($url_to_shorten, PHP_URL_SCHEME) )
{
require('framework/core/config.xml.php');
// check if the URL has already been shortened
$already_shortened = mysql_result(mysql_query('SELECT id FROM ' . DB_TABLE. ' WHERE long_url="' . mysql_real_escape_string(remove_http($url_to_shorten)) . '"'), 0);
if(!empty($already_shortened))
{
// URL has already been shortened
$shortened_url = getShortenedURLFromID($already_shortened);
}
else
{
// URL not in database, insert
mysql_query('LOCK TABLES ' . DB_TABLE . ' WRITE;');
mysql_query('INSERT INTO ' . DB_TABLE . ' (long_url, created, creator) VALUES ("' . mysql_real_escape_string(remove_http($url_to_shorten)) . '", "' . time() . '", "' . mysql_real_escape_string($_SERVER['REMOTE_ADDR']) . '")');
$shortened_url = getShortenedURLFromID(mysql_insert_id());
mysql_query('UNLOCK TABLES');
}
echo BASE_HREF . $shortened_url;
}
function getShortenedURLFromID ($integer, $base = ALLOWED_CHARS)
{
$length = strlen($base);
while($integer > $length - 1)
{
$out = $base[fmod($integer, $length)] . $out;
$integer = floor( $integer / $length );
}
return $base[$integer] . $out;
}

Convert anonymous function in PHP 5.3 into PHP 5.2 equivalent

I have error in line 2 and 13 in PHP 5.2, I have no idea to make the correction, I tried using create_function but not working, can anyone help with this?
function _process_special_keyword($str){
$callback = function($match){
$ret = $match[1] . '[' . $match[2] . ']';
if(!empty($match[3])){
$ret .= '.[' . $match[3] . ']';
}
$ret .= $match[4];
return $ret;
};
$strSQL = preg_replace_callback('/([\s\(\.,])(' . SPECIAL_KEYWORDS . ')(?:\.(' . SPECIAL_KEYWORDS . '))?([\s\)\.,])/i', $callback, $str);
$callback = function($match){
return 'CASE WHEN ' . $match[1] . ' THEN ' . $match[2] . ' ELSE ' . $match[3] . ' END';
};
$strSQL = preg_replace_callback('/if\s*\((.+),(.+),(.+)\)/i', $callback, $strSQL);
return $strSQL;
}
Thanks.
Error: Parse error: syntax error, unexpected T_FUNCTION
When using create_function(), the contents of the first argument should be a string representation of the PHP code that would fill the parentheses for the function declaration. The second argument should contain only the code inside the curly braces {} of the function declaration, the actual declaration itself should be omitted.
Try this code:
function _process_special_keyword($str){
$callback = create_function(
'$match',
'
$ret = $match[1] . "[" . $match[2] . "]";
if(!empty($match[3])){
$ret .= ".[" . $match[3] . "]";
}
$ret .= $match[4];
return $ret;
'
);
$strSQL = preg_replace_callback('/([\s\(\.,])(' . SPECIAL_KEYWORDS . ')(?:\.(' . SPECIAL_KEYWORDS . '))?([\s\)\.,])/i', $callback, $str);
$callback = create_function(
'$match',
'return "CASE WHEN " . $match[1] . " THEN " . $match[2] . " ELSE " . $match[3] . " END";'
);
$strSQL = preg_replace_callback('/if\s*\((.+),(.+),(.+)\)/i', $callback, $strSQL);
return $strSQL;
}
You can declare the callbacks outside of this function. Like this:
function _callback_one($match){
$ret = $match[1] . '[' . $match[2] . ']';
if(!empty($match[3])){
$ret .= '.[' . $match[3] . ']';
}
$ret .= $match[4];
return $ret;
}
function _callback_two($match){
return 'CASE WHEN ' . $match[1] . ' THEN ' . $match[2] . ' ELSE ' . $match[3] . ' END';
}
function _process_special_keyword($str){
$strSQL = preg_replace_callback('/([\s\(\.,])(' . SPECIAL_KEYWORDS . ')(?:\.(' . SPECIAL_KEYWORDS . '))?([\s\)\.,])/i', '_callback_one', $str);
$strSQL = preg_replace_callback('/if\s*\((.+),(.+),(.+)\)/i', '_callback_two', $strSQL);
return $strSQL;
}
Note: If these functions are in a class (meaning the function would be need to called like $this->_callback_one), pass an array as the "callback" parameter.
function _process_special_keyword($str){
$strSQL = preg_replace_callback('/([\s\(\.,])(' . SPECIAL_KEYWORDS . ')(?:\.(' . SPECIAL_KEYWORDS . '))?([\s\)\.,])/i', array($this, '_callback_one'), $str);
$strSQL = preg_replace_callback('/if\s*\((.+),(.+),(.+)\)/i', array($this, '_callback_two'), $strSQL);
return $strSQL;
}
according with object question, the faster way I think is something like so,
$f = <<<myfunc
\$ret = \$match[1] . '[' . \$match[2] . ']';
if(!empty(\$match[3])){
\$ret .= '.[' . \$match[3] . ']';
}
\$ret .= \$match[4];
return \$ret;
myfunc;
$callback = create_function('$match',$f);
note backslashes before $ and <<< FLAG FLAG; construct. In practice the answer of Rocket is more simple.

Optimizing PHP function

My language bar generation function looks like that. It works, but, feels like, it's not optimal way and this function has bunch of extra lines that can be removed. How you'd minify it?
public function generateLangs($url, $curlang, $langs) {
$i = 0;
$countlng = count($langs);
foreach ($langs as $lang) {
if (strstr($url, '?')) {
if (strstr($url, 'lang')) {
$newurl = preg_replace('&lang=(\w+)&', 'lang=' . $lang, $url);
} else {
$newurl = $url . '&lang=' . $lang;
}
}
else {
$newurl = $url . '?lang=' . $lang;
}
$result = '<a ';
if ($curlang == $lang) {
$result .= 'class="active" ';
}
$result .= 'href="' . $newurl . '">' . $lang . '</a>' . "\n";
if ($i != $countlng - 1)
$result .= ' | ';
echo $result;
$i++;
}
}
First of all you could make the language value a parameter of the URL by using a simple placeholder, like %s or %lang%:
$url = 'http://example.com/site/?lang=%lang%';
$newurl = str_replace('%lang%', $lang, $url);
You can either do this or you should encapsulate the logic to replace some query parameter of an URI into a function of it's own and use built-in functions in there instead rolling your own (e.g. parse_url, parse_str, ...).
Similar to that, same applies to your output, you could use the existing index (0 based I guess) and therefore streamline the whole:
public function generateLangs($url, $currentLanguage, $languages)
{
$urlPattern = preg_replace('~^(.*[?&]lang=)([a-z]+)((?:&.*)?)$~', '\1%lang%\3', $url, 1, $count);
$count || $urlPattern .= '?lang=%lang%';
unset($count);
foreach ($languages as $i => $lang)
{
$newUrl = str_replace('%lang%', $lang, $urlPattern);
printf("%s<a href=\"%s\"%s>%s</a>\n", $i ? ' | ' : '', $newUrl,
$curlang === $lang ? ' class="active"' : '', $lang);
}
}
The key point more or less is that you group code next to each other that belongs to each other. This more or less automatically reduces the complexity of the code and therefore often as well it's length. But take care that length is not that crucial, it's more important that you can read it cleanly.

Trouble with regular expression for comments code

I am currently making a homepage where logged in users can write comments. The comment string is first run through a function that str_replaces emoticons. After that I want it to exchange
[url=www.whatever.com]linktext[/url]
with:
<a href='www.whatever.com'>linktext</a>
The reason for this is that I want to strip the text for all the html code that isn't controlled by my comment code, in case some users decide to get creative-
and thought it would be best to use preg replace but the code I ended up with (Partially from reading about reg exp from my trusty "O reilly Sql and Php"-book and partially from the web) Is pretty bonkers, and most importantly, doesn't work.
Any help would be appreciated, thanks.
It's probably possible to exchange the entire code, not in 2 segments like I have done. Just decided on that getting 2 smaller parts to work first would be easier, and then merge them afterwards.
code:
function text_format($string)
{
$pattern="/([url=)+[a-zA-Z0-9]+(])+/";
$string=preg_replace($pattern, "/(<a href=\')+[a-zA-Z0-9]+(\'>)+/", $string);
$pattern="/([\/url])+/";
$string=preg_replace($pattern, "/(<\/a>)+/", $string);
return $string;
}
It looks like you're using something similar to BBCode. Why not use a BBCode parser, such as this one?
http://nbbc.sourceforge.net/
It also handles smilies, replacing them with images. If you use their test page, you will still see the text though, because they don't host the images and they set the alt-text to the smily.
I experimented a bit with the following:
function text_format($string)
{
return preg_replace('#\[url=([^\]]+)\]([^\[]*)\[/url\]#', '$2', $string);
}
However, one immediate fault with this is that if linktext is empty, there will be nothing between <a> and </a>. One way around it would be to do another pass with something like this:
preg_replace('##', '$1', $string);
Another option would be to use preg_replace_callback and put this logic inside your callback function.
Finally, this is obviously a common "problem" and has been solved many times by others, and if using a more mature open sourced solution is an option, I'd recommend looking for one.
#Lauri Lehtinen's answer is good for learning the idea behind the technique, but you shouldn't use it in practice because it would make your site extremely vulnerable to XSS attacks. Also, link spammers would appreciate the lack of rel="nofollow" on the generated links.
Instead, use something like:
<?php
// \author Daniel Trebbien
// \date 2010-06-22
// \par License
// Public Domain
$allowed_uri_schemes = array('http', 'https', 'ftp', 'ftps', 'irc', 'mailto');
/**
* Encodes a string in RFC 3986
*
* \see http://tools.ietf.org/html/rfc3986
*/
function encode_uri($str)
{
$str = urlencode('' . $str);
$search = array('%3A', '%2F', '%3F', '%23', '%5B', '%5D', '%40', '%21', '%24', '%26', '%27', '%28', '%29', '%2A', '%2B', '%2C', '%3B', '%3D', '%2E', '%7E');
$replace = array(':', '/', '?', '#', '[', ']', '#', '!', '$', '&', '\'', '(', ')', '*', '+', ',', ';', '=', '.', '~'); // gen-delims / sub-delims / unreserved
return str_ireplace($search, $replace, $str);
}
function url_preg_replace_callback($matches)
{
global $allowed_uri_schemes;
if (empty($matches[1]))
return $matches[0];
$href = trim($matches[1]);
if (($i = strpos($href, ':')) !== FALSE) {
if (strrpos($href, '/', $i) === FALSE) {
if (!in_array(strtolower(substr($href, 0, $i)), $allowed_uri_schemes))
return $matches[0];
}
}
// unescape `\]`, `\\\]`, `\\\\\]`, etc.
for ($j = strpos($href, '\\]'); $j !== FALSE; $j = strpos($href, '\\]', $j)) {
for ($i = $j - 2; $i >= 0 && $href[$i] == '\\' && $href[$i + 1] == '\\'; $i -= 2)
/* empty */;
$i += 2;
$h = '';
if ($i > 0)
$h = substr($href, 0, $i);
for ($numBackslashes = floor(($j - $i)/2); $numBackslashes > 0; --$numBackslashes)
$h .= '\\';
$h .= ']';
if (($j + 2) < strlen($href))
$h .= substr($href, $j + 2);
$href = $h;
$j = $i + floor(($j - $i)/2) + 1;
}
if (!empty($matches[2]))
$href .= str_replace('\\\\', '\\', $matches[2]);
if (empty($matches[3]))
$linkText = $href;
else {
$linkText = trim($matches[3]);
if (empty($linkText))
$linkText = $href;
}
$href = htmlspecialchars(encode_uri(htmlspecialchars_decode($href)));
return "$linkText";
}
function render($input)
{
$input = htmlspecialchars(strip_tags('' . $input));
$input = preg_replace_callback('~\[url=((?:[^\]]|(?<!\\\\)(?:\\\\\\\\)*\\\\\])*)((?<!\\\\)(?:\\\\\\\\)*)\]' . '((?:[^[]|\[(?!/)|\[/(?!u)|\[/u(?!r)|\[/ur(?!l)|\[/url(?!\]))*)' . '\[/url\]~i', 'url_preg_replace_callback', $input);
return $input;
}
which I believe is safe against XSS. This version has the added benefit that it is possible to write out links to URLs that contain ']'.
Evaluate this code with the following "test suite":
echo render('[url=http://www.bing.com/][[/[/u[/ur[/urlBing[/url]') . "\n";
echo render('[url=][/url]') . "\n";
echo render('[url=http://www.bing.com/][[/url]') . "\n";
echo render('[url=http://www.bing.com/][/[/url]') . "\n";
echo render('[url=http://www.bing.com/][/u[/url]') . "\n";
echo render('[url=http://www.bing.com/][/ur[/url]') . "\n";
echo render('[url=http://www.bing.com/][/url[/url]') . "\n";
echo render('[url=http://www.bing.com/][/url][/url]') . "\n";
echo render('[url= javascript: window.alert("hi")]click me[/url]') . "\n";
echo render('[url=#" onclick="window.alert(\'hi\')"]click me[/url]') . "\n";
echo render('[url=http://www.bing.com/] [/url]') . "\n";
echo render('[url=/?#[\\]#!$&\'()*+,;=.~] [/url]') . "\n"; // link text should be `/?#[]#!$&'()*+,;=.~`
echo render('[url=http://localhost/\\\\]d]abc[/url]') . "\n"; // href should be `http://localhost/%5C`, link text should be `d]abc`
echo render('[url=\\]][/url]') . "\n"; // link text should be `]`
echo render('[url=\\\\\\]][/url]') . "\n"; // link text should be `\]`
echo render('[url=\\\\\\\\\\]][/url]') . "\n"; // link text should be `\\]`
echo render('[url=a\\\\\\\\\\]bcde\\]fgh\\\\\\]ijklm][/url]') . "\n"; // link text should be `a\\]bcde]fgh\]ijklm`
Or, just look at the Codepad results.
As you can see, it works.

Categories