I have a large string example
newboay1fineboy8badboiy12 boy4andothersfollows...
my problem is how do i detect an incorrect boy from each of the string line output example my expected output should be like: boay1 boiy12 this my tried code:
$string = "newboay1fineboy8badboiy12 boy4andothersfollows...";
$string = preg_match_all("/bo\d+/", $string, $results);
foreach($results[0] as $val){
if($val !== boy) {
echo $val;
}
but i get no output in return. Big thanks for your time and impact in my soluction
You may fix you code as follows:
$string = "newboay1fineboy8badboiy12 boy4andothersfollows...";
$string = preg_match_all("/(bo\pL+)\d+/", $string, $results, PREG_SET_ORDER, 0);
foreach($results as $val){
if($val[1] !== "boy") {
echo $val[0] . "\n";
}
}
See the PHP demo.
The point is to match bo
, then any 1+ letters and capture that part, and then just match 1+ digits. See the regex (demo):
'~(bo\pL+)\d+~'
Details
(bo\pL+)
- Group 1: bo
and 1+ letters\d+
- 1+ digits.Inside the foreach
, $val[1]
contains the value captured into Group 1, and if it is not equal to boy
, you may get the whole match accessing $val[0]
in your if
statement.