Home > front end >  Find specific word in string and echo that specific word
Find specific word in string and echo that specific word

Time:01-11

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.

CodePudding user response:

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

  •  Tags:  
  • php
  • Related