简体   繁体   中英

substr to find all text before a wildcard substring

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, eg 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

Here is a working code snippet (with Devins Regexp):

$string = "I.Want.This.Bit.D00F00.Non.Of.This";
preg_match('/(.*)D[0-9]{2}F[0-9]{2}/', $string, $matches);
echo $matches[1];

Take a look at this question and answer on stack overflow.

How do I find the index of a regex match in a string?

You can run regex against D[0-9]{2}F[0-9]{2} to get the index of the D and then pass that into your substr and that will give you the first half. Only issue with this would be if there is for some reason your wildcard in the part that you want to keep.

Hope that helps!

您可以为此使用正则表达式( https://php.net/manual/en/book.pcre.php ),例如

$subString = preg_replace('~\.D\d{2}+F\d{2}\..*$~', '', $string);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM