How to extract a certain part of a string in PHP?

3

I have the following chains I need to extract only the countries

Roaming atv te da la bienvenida a Peru.Llamadas
Roaming atv te da la bienvenida a Reino Unido.Llamada
Roaming atv te da la bienvenida a Espana.Llamada
Roaming atv te da la bienvenida a Guadeloupe.Llamada

N Sometimes countries can repeat the same countries

I tried to try the following code:

$nombre = "Roaming atv te da la bienvenida a Peru.Llamadas";      
$arrayNombre = explode(" ", $nombre, 7);      

print_r($arrayNombre[6]);

The result is the following:

to Peru.Calls

I need to take the country out of that chain

    
asked by Juan Perez 05.11.2018 в 14:02
source

3 answers

8

I recommend you use strrpos() of php since it will return the position for which you need to divide the string and then use substr() to split the sentence.

Here's an example:

<?php
$array = ["Roaming atv te da la bienvenida a Peru.Llamadas","Roaming atv te da la bienvenida a Reino Unido.Llamada", "Roaming atv te da la bienvenida a Espana.Llamada"];
for($i=0; $i < count($array); $i++)
{
  //echo $array[$i]."\n ";
  $inicio = strrpos($array[$i], " a ") +3;
  $fin = strrpos($array[$i], ".");
  $fin = $fin - strlen($array[$i]);
  $pais = substr($array[$i], $inicio,  $fin);
  echo $pais . " \n";
}

?>
    
answered by 05.11.2018 в 14:35
7

The correct and scalable way is to use a regular expression to extract the full name of the country between the start ["a"] and end [".Calling"] strings. It works for all the examples.

<?php

$nombre = "Roaming atv te da la bienvenida a Reuno Unido.Llamada";

preg_match('/ a (.*?).Llamada/is', $nombre, $coincidencias);

print_r($coincidencias[1]); // Reino Unido

?>

Official documentation of preg_match in PHP.Net

    
answered by 05.11.2018 в 15:11
2

What I would do would be to make a explode for spaces in the text string, where I would divide the string and it would be saved in a array .

$cadena = "Roaming atv te da la bienvenida a Peru.Llamadas";
$cadenaExplode = explode(" ", $cadena);

The last element would be Peru.Llamadas . To collect it from array it is enough to obtain the last element:

$ultimoElemento = end($cadenaExplode);

And redo a explode per point:

$explodePais = explode(".", $ultimoElemento);
$pais = $explodePais[0]; // Este sería el país sólo
    
answered by 05.11.2018 в 15:32