Pattern not matching when string is at end

Viewed 45

I want to match the string which starts with '#' and ends with space or end of line. I am using the below function to find it.

function getStringsBetween($string, $start, $end)
{
$pattern = sprintf('/%s(.*?)%s/',preg_quote($start), preg_quote($end));
preg_match_all($pattern, $string, $matches);
return $matches[1];
}

I am using the below search

$y = "@!$+$+$+#+ hsjsjenshsjsjsj#hshsjsj ndjdjjdjdn #sem"
$output = getStringsBetween($y,"#"," ");
print_r($output);

the output looks like below.

Array ( [0] => + [1] => hshsjsj )

here it is missing #sem as it is end of the string and it doesn't match the pattern. How can i include end of the string to be space or end of line.

2 Answers

Change your pattern so it can have the $end value, or the end of the line $.

$pattern = sprintf('/%s(.*?)%s/',preg_quote($start), '(?:' . preg_quote($end) . '|$)');

https://3v4l.org/1oqhc

  • \s: Matches words that have a space after
  • $: Match the word that is at the end of the line

My code:

$input_lines = "@!$+$+$+#+ hsjsjenshsjsjsj#hshsjsj ndjdjjdjdn #sem"; 
preg_match_all('/#(.*?)(?:\s|$)/', $input_lines, $output_array);
print_r($output_array);

Result:

Array
(
    [0] => +
    [1] => hshsjsj
    [2] => sem
)
Related