Home > Back-end >  PHP: Find specific word in string and echo that specific word
PHP: 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 seperate 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 seperate variable. Similar to image boards.

Feel free to ask questions if this doesn't make sense :) Thanks in advance.

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