Regular expressions and matching [closed]
Asked Answered
C

2

12

Here is a list of examples of PHP regular expressions examples. Maybe this helps someone, as admin/ or another user can't make clear that I was trying to share my approaches.

preg_match does the search (preg_replace is a replacer).

preg_match has three parameters - preg_match(FindWhat, FindWhere, GivingOutput);

Example 1):

<?php
    // Everything expect letters and numbers
    $text = 'abc345fg@h';
    $newfilename = preg_match('/[^a-zA-Z0-9.]/', $text, $out);
    echo $out[0];
?>
Output will be:
@

preg_match finds only one result (the firstly found result), with two options: [0] or 1.

Example 2): find everything (any characters,words..) inside our search criteria:

<?php
    $text = 'abcdefghijklmnopqrst';
    $newfilename = preg_match('/ij(.*?)mn/', $text, $out);
    echo $out[0];
    echo $out[1];
?>
[1] -gives only the inner search result (what we had in the brackets,  between "ij" and "mn"):
kl

[0] -gives the whole search result:
ijklmn

(Note, that option 1 is not available if when you don’t use brackets in search criteria (as we have above, in example 1)

Example 3):

If your target text has many same occurrences, like this: $text = 'Hello user Jimmy Jones, it\'s me. Hello user Mery Pawders, it\'s still me.';

Now, here are two different matches, so, we need to use preg_match_all

<?php
    $text = 'Hello user Jimmy Jones, it\'s me. Hello user Mery Pawders, it\'s me.';
    $newfilename = preg_match_all('/hello user (.*?) it\'s/', $text, $out);
    foreach ($out[1] as $found_one) {
        echo $found_one;
    }
    // Or use $out[0] for full search match
?>

Output will be:
Jimmy Jones,
Mery Pawders,

Example 4): search among many possibilities:

<?php
    $text = 'member ACCOUNT7';
    preg_match("/ACCOUNT[123456789]/", $text, $out);
    echo $out[1];
?>

Output will be:
ACCOUNT7

Example 5): To find a string, while input text contains new lines, you must uses at the end;

<?php
    $text = 'one
    two
    three';
    preg_match("/one(.*?)three/s", $text, $out);
    echo $out[1];
?>

Output will be:
two

Example 6): Your search is always case sensitive. To make a case insensitive search, use i at the end (if you want, without s);

<?php
    $text = 'ONE TWO TREE';
    preg_match("/one(.*?)three/si", $text, $out);
    echo $out[1];
?>

Example 7): to search for special characters (like /".<*'?, etc.) inside preg_match, you need to use this escape sign: \

<?php
    $text = 'hello Jimmy/Kroger ';
    preg_match("/Jimmy\/Kroger/", $text, $out);
    echo $out[0];
?>

Now, we can use the ^ operator, which searches for results conversely.

Example 8): find everything rather than letters and numbers:

<?php
    $text = 'abc@*&^)($%';
    preg_match_all('/[^a-zA-Z0-9.]/', $text, $out);
    foreach ($out[0] as $varr) {
        echo $varr;
    }
?>
Output will be:
@*&^)($%

For search and replace, we have a bit different structure, as we need to use the new variable.

Example 9): find and replace everything rather than letters and numbers with other character, using this operator: ^

<?php
    $text = 'ab2sq)(&*(%$%^$@%n23f9';
    $variable = preg_replace('/[^a-zA-Z0-9.]/', 'a', $text);
    echo $variable;
?>
Output will be:
ab2sqn23f9

Example 10): search and add something inside the found results:

<?php
    $text = 'Hi, it\'s me, Niko from Austria';
    $variable = preg_replace('/(Niko.*?) from/', '$1 Gomez', $text);
    echo $variable;
?>
Output will be:

it's me, Niko Gomez Austria

Example 11): find all links inside text:

<?php
    $text = 'hi, my site is http://example.com, and on my page, at http://example.com/page37/blabla.html I wrote something..';
    preg_match_all("/[[:alpha:]]+:\/\/[^<>[:space:]]+[[:alnum:]\/]/",$text, $out);
    foreach($out[0] as $varr){
        echo $varr;
    }
?>
Output will be:
http://example.com
http://example.com/page37/blabla.html

Example 12): like the example 11 (but with replace) - find links in text and put them in anchored tags:

<?php
    $text = 'Hi, my site is http://example.com, and on my page, at http://example.com/page37/trid.html I wrote something..';
    $variable = preg_replace("/[[:alpha:]]+:\/\/[^<>[:space:]]+[[:alnum:]\/]/",'<a href="\\0">\\0</a>', $text);
    echo $variable;
?>

Output will be the same sentence, but the links will be anchored.

1) Tips: Do not use preg_match() if you only want to check if one string is contained in another string. Use stristr() or strpos() instead as they will be faster.

2) **More advanced, specific examples about PHP regular expressions, use Google, or see ** full options and manuals at - http://www.php.net/manual/en/reference.pcre.pattern.syntax.php

(You can review shortly all operators list here -
http://www.catswhocode.com/blog/15-php-regular-expressions-for-web-developers
http://www.noupe.com/php/php-regular-expressions.html
)

3) For HTML codes, there exist special light, PHP software, called- DOM Parser. But sometimes, if you know PHP regular expressions well, you might not need a DOM parser.

Create answered 23/4, 2013 at 10:17 Comment(1)
How would an email start with Shop and end with 0? SHOP_psgarden_0 is not a valid email address.Mucous
H
2

Try this regular expression:

/^Shop.*0$/i

This one checks for a Shop at the beginning and a zero at the end.

Hayseed answered 23/4, 2013 at 10:19 Comment(5)
but this one includes ^ mark. this means "opposite", doesnt it? also, the above answer with many examples, was very good, why you have been non-satisfied?Create
No it means beginning and the dollar sign the end of an input. See also this table in wikipedia: ^ Matches the starting position within the string. In line-based tools, it matches the starting position of any line. and $ Matches the ending position of the string or the position just before a string-ending newline. In line-based tools, it matches the ending position of any line.Hayseed
thanks. i have to check, what does the ^&$ marks do.Create
@solutionfix See: regular-expressions.info/reference.htmlDiscompose
@solutionfix just for improving my answers what was more helpful for you in the accepted answer?Hayseed
D
1

I assume, when you say "$email", that you mean the stuff before the @ sign. In that case you can use this regex:

$email = '[email protected]';
if (preg_match('/^shop.*0@/i', $email) === 1) {
    echo 'Yes!';
}

You can also check using normal procedural code:

$email   = '[email protected]';
$local   = substr($email, 0, strpos($email, '@'));
$amalgam = substr($local, 0, 4) . substr($local, -1);
if (strcasecmp('shop0', $amalgam) === 0) {
    echo "yes";
} else {
    echo "no";
}
Discompose answered 23/4, 2013 at 10:27 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.