Extract Text from a string in PHP

51 views Asked by At

I have a string which contains :

navigation pane or double clicking folders in the details pane.

Navigating the folder structure
-------------------------------
symbol will expand or collapse folders in the navigation pane

I want to extract text only "Navigating the folder structure"

I have tried with preg_match_all but unable to handle starting point which is a new line.

I also tried with strpos but unable to do with new line as starting point.

2

There are 2 answers

7
Dan On BEST ANSWER

Use a combination of strpos to find the line breaks, and substr to extract the text between the first and second line break. This text includes the dashes (-) so I included a str_replace to remove them.

$string = 'navigation pane or double clicking folders in the details pane.

    Navigating the folder structure
    -------------------------------
    symbol will expand or collapse folders in the navigation pane';

$position1 = strpos($string, "\n");
$position2 = strpos($string, "\n",$position1);

$extracted = str_replace("-","",substr($string, $position1, $position2));

echo $extracted;

This will print the desired text

3
jitendrapurohit On

Use explode -

$new =  explode("\n", $str);
var_dump($new[2]);