What I am trying to do is get all of the characters before a wildcard substring. For example, if I have the following string:
I.Want.This.Bit.D00F00.Non.Of.This
So, I want the output to be I.Want.This.Bit
The D
and the F
in D00F00
are always going to be there, but the integers inbetween will change. So it could be D13F02
, or D01F15
. The will not be more than 2 integers after the D
and the F
.
I had thought about doing the following, but then realised it would not work:
$string = "I.Want.This.Bit.D00F00.Non.Of.This"
$substring = substr($string, 0, strpos($string, '.D'));
The reason it would not work is because there is a chance the bit of the string I want to keep could have a .D
in it, e.g The.Daft.String.D03F12
. Using that example, all I would get is The
as the output, rather than The.Daft.String
.
Any guidance would be much appreciated.
Probably best to use preg_match for this since you want to capture a specific part of the string. Use regex capturing group.
<?php
$pattern = "/^([A-Za-z\.]+)\.D[0-9]{2}F[0-9]{2}/";
$subject = "I.Want.This.Bit.D00F00.Non.Of.This";
preg_match($pattern, $subject, $matches);
print_r($matches);
In this case the captured group you want will be in $matches[1].
You can play with/test the regex here: https://regex101.com/r/sM4wN9/1