Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extract characters occurring before one of several forbidden characters

I want to discard all remaining characters in a string as soon as one of several unwanted characters is encountered.

As soon as a blacklisted character is encountered, the string before that point should be returned.

For instance, if I have an array:

$chars = array("a", "b", "c");

How would I go through the following string...

log dog hat bat

...and end up with:

log dog h
like image 652
Philip Morton Avatar asked Jan 21 '26 21:01

Philip Morton


1 Answers

The strcspn function is what you are looking for.

<?php

$mask = "abc";

$string = "log dog hat bat";

$result = substr($string,0,strcspn($string,$mask));

var_dump($result);

?>
like image 119
Vinko Vrsalovic Avatar answered Jan 24 '26 12:01

Vinko Vrsalovic



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!