Most Useful common Regex collection


The most commonly used and useful regexes collection.

1) Trim trailing spaces
=> ^[\s]*(.*?)[\s]*$

2) Matches any valid HTML tag. (Not for nested tags)
=> <([a-z]+)([^<]+)*(?:>(.*)<\/\1>|\s+\/>)

3) Check for Hexadecimal value
=> \B#(?:[a-fA-F0–9]{6}|[a-fA-F0–9]{3})\b

4) Validate email ID
=> \b[\w.!#$%&’*+\/=?^`{|}~-]+@[\w-]+(?:\.[\w-]+)*\b

5) Username validation
Minimum length of 3, maximum length of 16, composed by letters, numbers or dashes.
=> /^[a-z0-9_-]{3,16}$/

6) Password checking
Moderate password - Minimum length of 6, at least one uppercase letter, at least one lowercase letter, at least one number, at least one special character
=> (?=^.{6,}$)((?=.*\w)(?=.*[A-Z])(?=.*[a-z])(?=.*[0-9])(?=.*[|!"$%&\/\(\)\?\^\'\\\+\-\*]))^.*

Strong password - Should have 1 lowercase letter, 1 uppercase letter, 1 number, 1 special character and be at least 8 characters long
=> /(?=(.*[0-9]))(?=.*[\!@#$%^&*()\\[\]{}\-_+=~`|:;"'<>,./?])(?=.*[a-z])(?=(.*[A-Z]))(?=(.*)).{8,}/

7) URL (http, https or ftp) checking
If you want to use capturing groups to get scheme, path, etc. (or add user-info, host, port…)
=> ^(((https?|ftp):\/\/)?([\w\-\.])+(\.)([\w]){2,4}([\w\/+=%&_\.~?\-]*))*$

8) IPv4 address validation
=> \b(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\b

9) Alpha-numeric, literals, digits, lowercase, uppercase chars only
\w                //alpha-numeric only
[a-zA-Z]          //literals only
\d                //digits only
[a-z]             //lowercase literal only
[A-Z]             //uppercase literal only

10) find an image with a specific source
enter image name to search img tags with specific image
=> /<img.*src=".*IMAGE-NAME-HERE".*?>/
eg:- preg_replace('/<img.*src=".*'.basename($img_path).'".*?>/', 'REPLACE-WITH', $string);
- here i am replacing image tags where image name matches.

11) find and replace all image tags
=> /<img[^>]+\>/i

12) remove specific html tags
remove any html tag, mention html tag without brackets.
=> /<\\/?HTML-TAG-HERE(.|\\s)*?>/

13) get image source from <img tag>
=> /^<\s*img[^>]+src\s*=\s*(["'])(.*?)\1[^>]*>$/

14) remove junk characters from string
=> '/[^(\x20-\x7F)\x0A\x0D]*/'
eg:- preg_replace('/[^(\x20-\x7F)\x0A\x0D]*/','', $string);

15) remove white spaces from string
=> /\s+/
eg:- preg_replace('/\s+/', '-', $string);
- here i am replacing spaces with '-'

16) remove non-alphanumeric character from string
=> /[^A-Za-z0-9\-]/
eg:- preg_replace('/[^A-Za-z0-9\-]/', '-', $galleryURL)
- here i am replacing any non alphanumeric character with '-'

17) remove a specific attribute from tags.
=> / attribute=("|\')(.*?)("|\')/
eg:- preg_replace('/ style=("|\')(.*?)("|\')/','',$string);
here i am replacing style attribute from html tags.

18) remove <script> tag from string
=> #<script(.*?)>(.*?)</script>#is
eg:- preg_replace('#<script(.*?)>(.*?)</script>#is', '', $string);
- here i am removing script tags from html string

19) replace shortcode (useful for wordpress)
=> /\[SHORTCODE_HERE id="([^"]*)"]/

20) Javascript Handlers
Inline JS handler => /\bon\w+=\S+(?=.*>)/
Inline JS handler with element => /(?:<[^>]+\s)(on\S+)=["']?((?:.(?!["']?\s+(?:\S+)=|[>"']))+.)["']?/

more to coming soon...

0 comments :

Create and Send Campaign Using MooSend API

<?php

$apikey = "<MOOSEND-API-KEY-HERE>";
$listID = "<MOOSEND-LIST-ID-HERE>";
$ep = "https://api.moosend.com/v3/";

$ch = curl_init();

$url = $ep."campaigns/create.json?Format=json&apikey=".$apikey;

$bulkPostFields = array (
  'Name' => '<CAMPAIGN-NAME-HERE>',
  'Subject' => '<CAMPAIGN-SUBJECT-HERE>',
  'SenderEmail' => '<SENDER-EMAIL-ID-HERE>',
  'ReplyToEmail' => '<SENDER-EMAIL-ID-HERE>',
  'ConfirmationToEmail' => '<SENDER-EMAIL-ID-HERE>',
  'MailingLists' => [
array (
'MailingListID' => "<MOOSEND-LIST-ID-HERE>",
'SegmentID' => "<MOOSEND-SEGMENT-ID-HERE>"
),
],
'WebLocation' => "PATH-TO-HTML-EMAILER",
);

curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($bulkPostFields));
curl_setopt($ch, CURLOPT_POST, 1);

$headers = array();
$headers[] = "Content-Type: application/json";
$headers[] = "Accept: application/json";
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

$result = curl_exec($ch);
if (curl_errno($ch)) {
echo 'Error:' . curl_error($ch);
}else{
$res = json_decode($result);
$campaignID = $res->Context;
}
curl_close ($ch);

//campaign send here
$ch = curl_init();

curl_setopt($ch, CURLOPT_URL, $ep."campaigns/".$campaignID."/send.json?apikey=".$apikey);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);

$headers = array();
$headers[] = "Content-Type: application/json";
$headers[] = "Accept: application/json";
$headers[] = "Content-Length: 0";
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

$result = curl_exec($ch);
if (curl_errno($ch)) {
echo 'Error:' . curl_error($ch);
}else{
echo $result;
}
curl_close ($ch);

?> 

0 comments :

Create and Send Campaign Using Active Campaign API


Coming Soon..

0 comments :

Create and Send Campaign Using SendGrid API

<?php

$apiKey = "<SENDGRID-API-KEY-HERE>";
     
        $html_content = file_get_contents($emailerpath);
        $html_content = str_replace("*|UNSUB|*", "[unsubscribe]", $html_content); //code to add unsubscribe link

        $titleText = 'AD Daily - ' . date("Y-m-d");
        $postFields = array('title' => '<CAMPAIGN-NAME-HERE>', 'subject' => '<CAMPAIGN-SUBJECT-HERE>', "sender_id" => "<SENDER-ID-HERE>",
            "list_ids" => array("<LIST-ID-HERE>"),
            "categories" => array("<CAMPAIGN-CATEGORY>"),
            "html_content" => $html_content,
            "plain_content" => $mail_subject . ' <a href="[unsubscribe]" style="text-decoration:none;" target="_blank"><span style="color: #000000;">Unsubscribe</span></a>',
            "suppression_group_id" => "<UNSUBSCRIBE-GROUP-ID-HERE>",
        );
        $aa = json_encode($postFields);

        //create a campaign using sendGrid
        $curl = curl_init();
        curl_setopt_array($curl, array(
            CURLOPT_URL => "https://api.sendgrid.com/v3/campaigns",
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_ENCODING => "",
            CURLOPT_MAXREDIRS => 10,
            CURLOPT_TIMEOUT => 30,
            CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
            CURLOPT_CUSTOMREQUEST => "POST",
            CURLOPT_POSTFIELDS => $aa,
            CURLOPT_HTTPHEADER => array(
                "authorization: Bearer " . $apiKey . "",
                "content-type: application/json"
            ),
        ));
        $response = json_decode(curl_exec($curl));
        $err = curl_error($curl);
        curl_close($curl);
     
        if ($err) {
            echo "<br/>cURL Error #:" . $err;
        } else {
            $campaignID = $response->id;
        }

//send a campaign using sendGrid
        if (isset($campaignID) && $campaignID != "") {
            echo " campaignID ==> " . $campaignID;
            $curl = curl_init();

            curl_setopt_array($curl, array(
                CURLOPT_URL => "https://api.sendgrid.com/v3/campaigns/" . $campaignID . "/schedules/now",
                CURLOPT_RETURNTRANSFER => true,
                CURLOPT_ENCODING => "",
                CURLOPT_MAXREDIRS => 10,
                CURLOPT_TIMEOUT => 30,
                CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
                CURLOPT_CUSTOMREQUEST => "POST",
                CURLOPT_POSTFIELDS => "null",
                CURLOPT_HTTPHEADER => array(
                    "authorization: Bearer " . $apiKey . "",
                    "content-type: application/json"
                ),
            ));

            $response = curl_exec($curl);
            $err = curl_error($curl);

            curl_close($curl);

            if ($err) {
                echo "<br/>cURL Error #:" . $err;
            } else {
                echo '<br/>Operation completed without any errors <br/>';
                echo $response;
            }
        }

?>

0 comments :

Create and Send Campaign Using Mailchimp API


<?php

//Include MailChimp API version 3 Class Library
include('mcv3/src/MailChimp.php');

use \DrewM\MailChimp\MailChimp;
$MailChimp = new MailChimp('<MAILCHIMP-API-KEY-HERE>');

//create campaign at Mailchimp
$result = $MailChimp->post('campaigns', array(
            "type" => 'regular',
            "recipients" => array(
                "list_id" => "<LIST-ID-HERE>",
                "segment_opts" => array(
                    "match" => "any",
                    "conditions" => array(
                        array("field" => "interests-<INTEREST-GROUP-ID-HERE>", "op" => "interestcontains", "value" => ["<INTEREST-ID-HERE>"])
                    ),
                )
            ),
            'settings' => array(
                'subject_line' => '<CAMPAIGN-SUBJECT-HERE>',
                'title' => '<CAMPAIGN-NAME-HERE>',
                'from_name' => '<FROM-NAME-HERE>',
                'reply_to' => '<FROM-EMAIL-ID-HERE>',
                'auto_footer' => false
            ),
            'content' => array('url' => $emailerpath),
        ));
        $campaign_id = $result['id'];

        //sleep for Sometime
        sleep(20);

//put content to campaign
        $contentx = json_encode($MailChimp->put('/campaigns/' . $campaign_id . '/content', array('url' => $emailerpath)
        ));

        //sleep for Sometime
        sleep(20);

//send email to list
        echo json_encode($MailChimp->post('/campaigns/' . $campaign_id . '/actions/send'));

?>

0 comments :