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<?php
  $str = 'aaa aaa aaa';
  $res = preg_replace('#^aaa#', '!', $str);
?>

As a result, the following will be written to the variable:

php'! 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<?php
  $str = 'aaa aaa aaa';
  $res = preg_replace('#aaa$#', '!', $str);
?>

As a result, the following will be written to the variable:

php'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<?php
  $str = 'aaa';
  $res = preg_replace('#^a+$#', '!', $str);
?>

As a result, the following will be written to the variable:

php'!'

Practice Tasks

Задание 1

Given a string:

php<?php
  $str = 'abc def xyz';
?>

Write a regex that will find the first substring of letters.

Задание 2

Given a string:

php<?php
  $str = 'abc def xyz';
?>

Write a regex that will find the last substring of letters.

Задание 3

Given a string:

php<?php
  $str = '$aaa$ $bbb$ $ccc
';
?>

Write a regex that will find the last substring of letters surrounded by dollar symbols.