Start and End of String in PHP Regex
There are special symbols that denote
the start ^
or the end of a string $
.
Let's look at their work with examples.
Example
In this example, the search pattern is as follows: replace
'aaa'
with '!'
only if it
is at the beginning of the string:
<?php
$str = 'aaa aaa aaa';
$res = preg_replace('#^aaa#', '!', $str);
?>
As a result, the following will be written to the variable:
'! aaa aaa'
Example
In this example, the search pattern is as follows: replace
'aaa'
with '!'
only if it
is at the end of the string:
<?php
$str = 'aaa aaa aaa';
$res = preg_replace('#aaa$#', '!', $str);
?>
As a result, the following will be written to the variable:
'aaa aaa !'
Example
When ^
is at the beginning of the regex,
and $
is at the end, then in this way we
check the entire string for compliance with
the regex.
In the next example, the search pattern is as follows:
the letter 'a'
repeats one or
more times, replace the entire string with '!'
only if it consists entirely of letters 'a'
.
<?php
$str = 'aaa';
$res = preg_replace('#^a+$#', '!', $str);
?>
As a result, the following will be written to the variable:
'!'
Practice Tasks
Given a string:
<?php
$str = 'abc def xyz';
?>
Write a regex that will find the first substring of letters.
Given a string:
<?php
$str = 'abc def xyz';
?>
Write a regex that will find the last substring of letters.
Given a string:
<?php
$str = '$aaa$ $bbb$ $ccc
';
?>
Write a regex that will find the last substring of letters surrounded by dollar symbols.