Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

PHP: 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 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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Feel free to ask questions if this doesn’t make sense 🙂 Thanks in advance.

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading