New PHP 5.3 solution to replace ereg and eregi functions

Forgive my ignorance but regex code is beyond my comprehension.

I came across this function in a php module that was not authored by me:

function isURL($url = NULL) {
    if($url == NULL) return false;

    $protocol = '(http://|https://)';
    $allowed = '([a-z0-9]([-a-z0-9]*[a-z0-9]+)?)';

    $regex = "^". $protocol . // must include the protocol
                     '(' . $allowed . '{1,63}\.)+'. // 1 or several sub domains with a max of 63 chars
                     '[a-z]' . '{2,6}'; // followed by a TLD
    if(preg_match("/$regex/", $url)) return true;
    else return false;
}

Could someone please assist me in updating this code to replace the eregi function?

Answer №1

Great question - this information is crucial for those transitioning to PHP 5.3, as the ereg and eregi functions have been deprecated. To make the switch,

eregi('pattern', $string, $matches) 

should be replaced with

preg_match('/pattern/i', $string, $matches)

(the additional i in the first argument indicates case-insensitivity and mirrors the behavior of eregi - simply ignore it when replacing an ereg call).

It's important to note the differences between old and new patterns! Refer to this page for a list of primary distinctions. For more complex regular expressions, delve deeper into disparities between POSIX regex (used by the previous ereg/eregi/split functions etc.) and PCRE.

In your specific scenario, confidently substitute the eregi call with:

if (preg_match("%{$regex}%i", $url))
    return true;

(notice: the % serves as a delimiter; although the slash / is typically used. Ensure that the delimiter isn't within the regex or escape it. Since slashes are present in $regex in your example, opting for a different character as the delimiter is more practical.)

Answer №2

Ensure your code remains functional by using Palliative PHP 5.3 until all deprecated functions are replaced

if(!function_exists('ereg'))            { function ereg($pattern, $subject, &$matches = []) { return preg_match('/'.$pattern.'/', $subject, $matches); } }
if(!function_exists('eregi'))           { function eregi($pattern, $subject, &$matches = []) { return preg_match('/'.$pattern.'/i', $subject, $matches); } }
if(!function_exists('ereg_replace'))    { function ereg_replace($pattern, $replacement, $string) { return preg_replace('/'.$pattern.'/', $replacement, $string); } }
if(!function_exists('eregi_replace'))   { function eregi_replace($pattern, $replacement, $string) { return preg_replace('/'.$pattern.'/i', $replacement, $string); } }
if(!function_exists('split'))           { function split($pattern, $subject, $limit = -1) { return preg_split('/'.$pattern.'/', $subject, $limit); } }
if(!function_exists('spliti'))          { function spliti($pattern, $subject, $limit = -1) { return preg_split('/'.$pattern.'/i', $subject, $limit); } }

Answer №3

Are you looking for a more efficient alternative to preg_match and eregi?

if(!filter_var($URI, FILTER_VALIDATE_URL))
{ 
return false;
} else {
return true;
}

Or maybe for validating email addresses:

if(!filter_var($EMAIL, FILTER_VALIDATE_EMAIL))
{ 
return false;
} else {
return true;
}

Answer №4

The use of <code>eregi in PHP is now deprecated, and you should use preg_match instead.

function validateURL($url)
{
    return preg_match('%^((https?://)|(www\.))([a-z0-9-].?)+(:[0-9]+)?(/.*)?$%i', $url);
}


if(validateURL("http://google.com"))
{
    echo "Good URL" ;
}
else
{
    echo "Bad Url" ;
}

For more information, please refer to http://php.net/manual/en/function.preg-match.php Thank you!

:)

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Swapping Codeigniter sessions among users

Recently, I encountered a perplexing issue on one of my client's websites where it appeared that two users' sessions were being interchanged. The website is built using CodeIgniter and configured with the following settings: $config['sess_c ...

No content appearing instead of AngularJS code displayed

My goal is to retrieve data from a MySQL database using PHP and then pass that data in JSON format to AngularJS for display in a table. The HTML code looks like this: <body ng-app="myModule"> <div class="row"> <div class="col-lg-12 ...

Deactivate the Submit button when the database field has been populated

My form includes a submit button. The Submit button should be disabled if the "price" for a specific product is already filled: PHP Code <?php $host="localhost"; $username="root"; $password=""; $db_name="ge"; $con=mysqli_connect("$h ...

Unable to make any updates to the MySQL database

Currently, I am in the process of developing a login system using PHP. One of the features I am working on is a password recovery script that involves generating random codes with an expiration date. However, when attempting to store the generated random c ...

Tips for invoking the controller's update method

I have been encountering an issue while attempting to utilize the update function of my controller on the dashboard.blade.php page. Upon clicking "Save", instead of updating, the page switches to show.blade.php. Content of my dashboard.blade.php: ...

PHP function to write CSV data to a file results in an empty file being

My csv data has the following structure: $data = 'email,score <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="73191c1b1d33171c5d101c1e">[email protected]</a>,3 <a href="/cdn-cgi/l/email-protection" class ...

Execute and generate a continuous loop in JavaScript

I successfully implemented an image slider using pure PHP, but encountered issues when integrating it into Yii framework. The images were not loading due to the following reasons: - JavaScript block was not loading image numbers. - I am unsure how to load ...

What is the process for deleting the model column in an email invoice on Opencart?

I want to completely remove the "model" column from all aspects of the Opencart admin and email notifications. I have already taken steps to remove it from admin >> view >> template >> sales >> order_invoice.tpl, but it did not wo ...

Deleting database information using Jquery when a div is clicked

I'm looking to create an alert system where users will see a pop-up alert on their screen. However, I am facing a major issue in removing the div completely. I understand that I need to remove it from the database, but I'm struggling with finding ...

There is no binary content for the PDF file

Utilizing the Sonata Media Bundle, I allow users to upload PDF files. My goal is to utilize Imagick in order to generate a preview image of a pdf document. I have a $media object that contains details about my pdf. Upon running die(dump($media)), I can ob ...

What is the best method for incorporating line breaks into JSON output?

Here is the ajax code snippet that returns a single line like this: appleorangebanana My goal is to display it as clickable links in a list like this: apple orange banana I'm still learning about ajax and json, so any help ...

Leveraging PHP for efficiently storing images in a directory and simultaneously inserting descriptions into a database

The user has chosen to upload several images for their classified listing. Here's what needs to be accomplished: Upload the images with descriptions for each image - COMPLETE Save the images to a specified folder Store the image location and descript ...

Visualization of XML Datamarkup

I am facing an issue with a function that generates XML from a source. Everything works perfectly except for when certain fields are too long, causing the table to stretch and mess up the website formatting. Is there a way to automatically insert line brea ...

Slim authentication not providing responses

I've set up basic authentication with Slim and REST. I installed the Composer package for basic auth and used the following code: <?php require 'confing.php'; require 'Slim/Slim.php'; \Slim\Slim::registerAutoloader() ...

interactive textbox created with the combination of javascript and php

Hello, I am new to JavaScript and jQuery. I am trying to create a dynamic text box using JavaScript that can add and remove rows. When I press the add button, it works well, but when I pressed delete, it deleted the entire table. Below is my JavaScript fu ...

Guide on uploading multipart career-form data with file paths and validation in CodeIgniter with the help of AJAX

I am facing an issue while attempting to insert job form data with file uploading and validation in PHP CodeIgniter via AJAX. The code I am using is provided below, but unfortunately, it's not functioning as expected. Can anyone help me figure out how ...

Building a powerful Laravel 5 application deployed on Bluemix platform

I am facing challenges when trying to deploy my Laravel app to Bluemix using Laravel versions 4.2 and 5.0. Here is the error from the Bluemix logs: 2015-05-01T16:52:49.71+0100 [STG/0] ERR [UnexpectedValueException] 2015-05-01T16:52:49.71+0100 [STG/0] ERR ...

Is there a way to run both PHP and HTML code using the eval function?

Is it possible to execute HTML and PHP simultaneously using the eval function? eval ("<center> this is some html </center>"); The above code does not yield the desired output, so I am considering changing it to: echo ("<center> this is ...

Error initializing AWS Transcribe PHP API 3.0 - Unable to Initialize API

I'm currently working on setting up the API for AWS Transcribe, but I'm facing some confusion with the documentation. Below is my code: <?php require 'aws-api/aws-autoloader.php'; $client = new Aws\TranscribeService\T ...

Transfer your documents effortlessly as soon as they are

I am having trouble implementing an automatic file upload feature without the need for a separate upload button. Below is the code I have so far, excluding the irrelevant CSS. //html <!-- some codes here--> <input type="file" id="f ...