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 Regex: How to match the word before dash?

Here’s my code, but it’s not working. How can I match the word before dash?

$str = '-Lorem Ipsum is simply dummy- text of the printing';
preg_match('/(.*)\-/', $str, $matches);

Expected Output: dummy

Thanks a lot for your help!

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

>Solution :

Try this:

preg_match('/([\S]+)\-/', $str, $matches);

echo ($matches[1] ?? null);

The \S means "Any non-whitespace character". So it’s kind of like saying "Match one or more non-whitespace characters up to a hyphen."

Test it out at regex101: https://regex101.com/r/E3gOqm/1

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