0

I am trying to take (to later delete) the text after a specific character for example:

$char = "This is an example text but this text needs it\n this text no longer";

I only want the text before the "\n" after that I want to delete it

EDIT:

I want you to return something like this:

This is an example text but this text needs it
Dylan Stark
  • 2,325
  • 17
  • 24
IrvinS
  • 11
  • 2

3 Answers3

1

You can explode the string with the specific character and display only first part. Considering your example string you can code like this.

$char = 'This is an example text but this text needs it\n this text no longer';

$string = explode('\n',trim($char));
echo $string[0];

Out put:

This is an example text but this text needs it
Ravinder Reddy
  • 3,869
  • 1
  • 13
  • 22
1

Use strpos to locate the first instance of a specific, character, then substr to return to that offset.

$string = "This is an example text but this text needs it\n this text no longer";
if( ( $length = strpos( $string, "\n" ) ) !== false )
{
  $string = substr( $string, 0, $length );
}
echo $string;
Scuzzy
  • 12,186
  • 1
  • 46
  • 46
1
$before_newline = strtok($char, "\n");

The strtok() function can be used to achieve this. In the case where the newline character does not appear in the string, the result will be the whole string. Otherwise, it is the portion of the string before the newline character.

salathe
  • 51,324
  • 12
  • 104
  • 132