Examples of regular expressions in PHP

PHP Examples of the regular expressions

Content

  1. How to get a substring inside the brackets from the string?
  2. How to substitute a substring inside the brackets in a string taking the ending standing right after the closing bracket?
  3. How to get a value of variable from url using regular expression PHP?
  4. How to cut out text inside a tag?
  5. Exploding, cutting an src attribute of the img tag from the text
  6. Exploding, cutting an img tag from the text together with the attributes


How to get a substring inside the brackets from the string?

For instance, there is a string of the following kind:

<?php

$phrase = '{preg_match} - that performs a regular expression match.'; 
preg_match("/{([^}]+)}*/i", $phrase, $found);
print_r($found); 

?>

We used the function preg_match to solve this task. We will get the following result:

Array 
    )
        [0] => {preg_match} 
        [1] => preg_match 
    )

Our substring is in the second element of the array $found. Besides, it is possible to set a regular expression for work, for instance, with various kinds of brackets. If we need to get a substring in square brackets, let’s change the regular expression in the following manner:

<?php

$phrase = '[preg_match] - that performs a regular expression match'; 
preg_match("/[ # opening square bracket
       ([
       ^] # to take from the beginning of the string till the bracket    
       ]+)
       ] # closing square bracket 
       */i", $phrase, $found);
print_r($found); 

?>

We changed the regular expression in three places. We will get the same result as in the first example.

How to substitute a substring inside the brackets in a string taking the ending standing right after the closing bracket?

Let’s use the function preg_replace to solve this task.

<?php

$str = "Searches {sub}ject for matches...";
$phrase = preg_replace('/{ # opening curly bracket
        (.*)     # to take any symbols inside the brackets  
        }    # cloasing curly bracket 
        ([^s]*) # to take all symbols after the closing  
             # curly bracket except for a space 
        /', '$1$2', $str); 
echo $phrase;

?>


As you can see, what we need to take from inside curly brackets and outside them is separated with round brackets. We have two conditions, the first in the first round brackets, the second one, in the second. Inside the function which will carry out the operation with the string using the above conditions the coincidence will be momorized in special variables, therefore these variables can be addressed through $1 and $2.These two variables are indicated in the second argument of function preg_replace. As a result we will get:

Searches <em>subject</em> for matches... 

How to get a value of variable from url using regular expression PHP?

Use the function preg_match to solve this problem.

<?php

$url = 'http://www.softmaker.kz.php?cat=2&id=2'; 
// we'll get a value of variable $cat
preg_match("/
    ?
    (?:.*&)*
    cat=
    ([^&]+)
    /i", $url, $found);
echo $found[1];

// we'll get a value of variable $id
preg_match("/
    ?
    (?:.*&)*
    id=
    ([^&]+)
    /i", $url, $found);
echo $found[1];

?>

A value of variable is in the second element of array $found. Besides, to solve this problem it is possible to use two functions php parse_url and parse_str.

<?php

$arr=parse_url('http://www.softmaker.kz.php?cat=2&id=101');
parse_str($arr['query'], $arr2);
print_r($arr2); 

?>

We’ll get the following result:

Array 
    )
        [cat] => 2 
        [id ] => 101 
    )

How to cut out text inside a tag?

We have a text inside a tag:
<head>

a formated text

</head>

We need to get:

a formated text

Use function preg_match:

<?php

$matches = null;
$firstStr = '<head>
        ...
        a formated text
        ...
         </head>';
$returnVal = preg_match('/<head>(.*)<\/head>/s', $firstStr, $matches);
print_r($matches);

?>

We’ll get the following result:

Array 
    )
        [0] => '<head>
              ...
              a formated text
              ...
            </head>'
        [1] => '...
            a formated text
            ...' 
    )


It is clear that we can replace a tag head, for inctance with a tag p, in order to search text in it.

Exploding, cutting an src attribute of the img tag from the text

Use the function preg_match_all:

<?php

    $matches = null;
    // Cuts from the text only src, i.e. only the reference to the image 
    preg_match_all('/<img[^>]+src=([\'"])?((?(1).+?|[^\s>]+))(?(1)\1)/', 
    $myrow[text], $matches);
    echo "<pre>";
    print_r($matches[2]);
    echo "</pre>";

?>

We receive the following result:

Array
(
    [0] => \"https://site.softmaker.kz/Forma-zadolzhennost-pered-postavshhikami-i-pokupatelyami.png\"
    [1] => \"https://site.softmaker.kz/VyborPerioda-nastrojka-otchyota.png\"
    [2] => \"https://site.softmaker.kz/OtborKontragenta-nastrojka-otchyota.png\"
    [3] => \"https://site.softmaker.kz/OtborGruppyKontragentov-nastrojka-otchyota.png\"
)

Exploding, cutting an img tag from the text together with the attributes

Use the function preg_match_all:

<?php

    // Cuts from the text all img tags
    //together with all attributes  alt, title etc.
    $text = $myrow[text];
    preg_match_all('/<img[^>]+>/i', stripslashes($text), $matches);
    $bodytag = $matches[0];
    echo "<pre>";
    print_r($bodytag[0]);
    echo "</pre>";
    
?>

We receive the following result:

Array
(
[0] => <img 
src="https://site.softmaker.kz/Forma-zadolzhennost-pered-postavshhikami-i-pokupatelyami.png" 
    width="508" height="354" 
    title="Внешний вид отчета 1С «Задолженность перед ...»"
    alt="Отчет 1С для конфигурации 1С Бухгалтерия 8.2. 
    «Задолженность перед поставщиками и покупателями»"/>
[1] => <img src="https://site.softmaker.kz/VyborPerioda-nastrojka-otchyota.png" 
    width="431" height="253" 
    title="Диалог «Настройка отчёта» для выбора значения периода"
    alt="Настройка отчета «Задолженность ..."/>
[2] => <img src="https://site.softmaker.kz/OtborKontragenta-nastrojka-otchyota.png" 
    width="557" height="231" 
    title="Диалог «Настройка отчёта» для выбора значения ..."
    alt="Настройка отчета «Задолженность ..."/>
[3] => <img 
    src="https://site.softmaker.kz/OtborGruppyKontragentov-nastrojka-otchyota.png" 
    width="512" height="231" 
    title="Диалог «Настройка отчёта» для выбора ..."
    alt="Настройка отчета «Задолженность перед поставщиками ..."/>
)