What are some best practices for using regular expressions in PHP to avoid cutting out unintended parts of text?

When using regular expressions in PHP, it's important to be specific in your pattern matching to avoid unintentionally cutting out parts of text. One way to do this is by using anchors such as ^ (start of string) and $ (end of string) to ensure that the pattern matches the entire string rather than just a part of it. Additionally, using word boundaries (\b) can help to match whole words and avoid cutting out partial words.

$text = "This is a sample text with some numbers like 12345 and words like PHP";
$pattern = "/\b\d+\b/"; // Match whole numbers
preg_match_all($pattern, $text, $matches);

foreach ($matches[0] as $match) {
    echo $match . "\n";
}