Liambails1
Liambails1

Reputation: 45

Find specific word in string and echo that specific word

I'm trying to check if a variable has a number that starts with >> i.e., >>12345 and then separate that number into a different variable.

For example:

$my_string = "
>>12345

Hello this is an example string.
";

I'd like to store the '>>12345' in the database as a separate variable. Similar to image boards.

Upvotes: 1

Views: 51

Answers (1)

This is easily done with a regular expression:

<?php

$my_string = "
>>12345

Hello this is an example string.
";
preg_match("/(>>\d+)/", $my_string, $matches);
echo $matches[1];

The Regex looks for >>followed by any number of numeric digits, then captures that group into the $matches array.

Demo: https://3v4l.org/cKE6J

Upvotes: 3

Related Questions