I need to extract a substring from a string that meets a number of conditions . I have almost succeeded, but I have an error in the regular expression and I do not finish obtaining the desired result.
I receive a string, with a long name of a rate, along with a letter and version number. For example: "NAME RATE V1 12M". I need to keep only the "V1" part.
It will always follow the pattern: - A letter (in principle capitalized, although I would like to accept both), in my case it will always be the letters: V, L, M. - Always followed by a number that starts at 0 and can be up to 2 digits . Here I have my problem, when it is a figure, it extracts the substring correctly, when it is 2 figures it fails and it does not extract it, it does not find a match.
I leave you what I have so far with some examples included:
$var1 = "TARIFA 1.1 NOMBRE TARIFA V1 12M";
$var2 = "TARIFA LDVB8 NOMBRE V5 10M";
$var3 = "TARIFA HD76 V10 12M";
$var4 = "TARIFA NOMBRE4 L3 18M";
$var5 = "TARIFA NOMBRE5 L10 12M";
$var6 = "NO HAY COINCIDENCIA";
$var7 = "TARIFA NOMBRE7 M6 12M";
function extractV($str) {
if (preg_match('/ [V|L|M][0-9]? /',$str,$coincidencias,PREG_OFFSET_CAPTURE)) {
//Hay coincidencia
$valorBuscado = $coincidencias[0];
$version = $valorBuscado[0];
}
else
{
$version = "NO";
}
return $version;
}
$extraccion1 = extractV($var1);
echo "<br>Coincidencias1 = ". $extraccion1;
$extraccion2 = extractV($var2);
echo "<br>Coincidencias2 = ". $extraccion2;
$extraccion3 = extractV($var3);
echo "<br>Coincidencias3 = ". $extraccion3;
$extraccion4 = extractV($var4);
echo "<br>Coincidencias4 = ". $extraccion4;
$extraccion5 = extractV($var5);
echo "<br>Coincidencias5 = ". $extraccion5;
$extraccion6 = extractV($var6);
echo "<br>Coincidencias6 = ". $extraccion6;
$extraccion7 = extractV($var7);
echo "<br>Coincidencias7 = ". $extraccion7;
As you can see, in the $var3
and $var5
, it does not extract value (because the number that follows the letter is 2 figures), but it should. How can I correct the RegEx? Or any solution for substring extraction with those features? Thank you!
You're just asking for a numeric character followed by a space, which doesn't hold if there are two.
It should be instead
to accept either one or two figures. I also wrapped it in parentheses so that the second element of the array is the captured group without the spaces.