Replace text in PHP

1

I have a question, I have a sentence that I need to eliminate certain content, but respecting the whole sentence. For example, the idea is to eliminate the characters that come after the word por .

$string = "Hace hoy un buen día para pasear por 3 forques, y lo que sea.";

What I need you to return the phrase as follows:

Hace hoy un buen día para pasear

I'm doing it this way but I can not think of how to recover the sentence ..

preg_match("/por [0-9]{0,3}.+/", $string , $resultado);
// Devuelve-> "por 3 forques, y lo que sea."

What step am I missing?

    
asked by Fumatamax 07.02.2018 в 13:20
source

2 answers

6
  

delete the characters after the word por [...] but respecting the whole sentence.

You are looking to delete, not match something. To remove, we need to replace with preg_replace () .

mixed preg_replace ( mixed $pattern , mixed $replacement , mixed $subject [, int $limit = -1 [, int &$count ]] )


And we use the following regex to match a space, por as full word ( \b matches word limits), and then any number of characters that are not points or line breaks (so we consume until the end of the sentence). In this way, we respect the end point of the sentence.

/ por\b[^.\r\n]*/iu

Or if you want to delete from por to the end of the text:

/ por\b.*/isu
  • The s modifier is for .* to also match line breaks.
  • The u modifier is for \b to include Unicode characters when searching for the word limit.
  • The i modifier is to ignore uppercase / lowercase when searching por .


Code:

$string = "Hace hoy un buen día para pasear por 3 forques, y lo que sea.";

$resultado = preg_replace ( '/ por\b[^.\r\n]*/iu' , '' , $string );

echo $resultado;

Result:

Hace hoy un buen día para pasear.
    
answered by 07.02.2018 / 14:24
source
1

Very easy:

$text = "Hace hoy un buen día para pasear por 3 forques, y lo que sea.";
$part = strstr($text," por ");
$nuevoTexto = str_replace($part,"",$text);
echo $nuevoTexto;

You could also deal with:

$text = "Hace hoy un buen día para pasear por 3 forques, y lo que sea.";
$pos = strpos($text," por ");
$nuevoTexto = substr($text,0,$pos);
echo $nuevoTexto;

I hope I help you.

Greetings.

    
answered by 07.02.2018 в 15:38