PHP do a search and extract in another variable

0

Good I am trying to do one thing, I explain myself: Of a variable type text with several lines I want to extract in another variable the line that contains something

I've tried it in the following way:

$reporte strrpos(substr('$TextoGrande', -1, 0),'texto a buscar'); 

but it does not work for me, any suggestions? By the way, I have this line, in case it works:

$TextoGrande = trim($Todo);

let's say that what I want is to put in the report variable all the complete lines that match the text to be searched

Thanks

    
asked by pablo 07.05.2018 в 16:50
source

1 answer

1

There are many ways to do it, the simplest one that occurs to me is:

<?php
    $lineas = "línea 1 con algo de texto\n";
    $lineas .= "línea 2 con algo de texto\n";
    $lineas .= "línea 3 sin a_l_g_o de texto\n";
    $lineas .= "línea 4 sin a_l_g_o de texto\n";
    $lineas .= "línea 5 con algo de texto\n";

    echo "<ul>";
    $ret = explode("\n", $lineas);
    foreach($ret as $linea) {
        $pos = strpos($linea, "algo");
        if ($pos === false) {
            // No se encontró
        } else {
            echo "<li>" . $linea . "</li>";
        }
    }
    echo "</ul>";
?>

That will show the following result:

línea 1 con algo de texto
línea 2 con algo de texto
línea 5 con algo de texto

If instead of showing it, you want to add it in another array, you could delete the echo and in the else part of the if put something like:

$arr[] = $linea;

Having previously declared the $ arr as array.

    
answered by 07.05.2018 / 17:00
source