A combination of explode, substr, and strpos can do it:
Split the string by #
, then get the string between #
and the first .
by using substr
and strpos
.
<?php
$examples = [
'The time is over. # its mean I\'m need to die.',
'Please help me. # Ghost. I am here alone.',
'Sorry. # help yourself.'];
foreach($examples as $example) {
$exploded = explode('#', $example);
$substr = trim(substr($exploded[1], 0, strpos($exploded[1], '.')));
var_dump($substr);
}
In a function for one specific string:
$test = parseString('Sorry. # help yourself.');
function parseString($string) {
$exploded = explode('#', $string);
$substr = trim(substr($exploded[1], 0, strpos($exploded[1], '.')));
return $substr;
}
var_dump($test);
With string input we have to do an additional step that is breaking by \n
before:
$stringExample = "The time is over. # its mean I'm need to die.
Please help me. # Ghost. I am here alone.
Sorry. # help yourself.";
$test2 = parseString2($stringExample);
function parseString2($string) {
$result = [];
$array = explode("\n", $string);
foreach($array as $a) {
$exploded = explode('#', $a);
$substr = trim(substr($exploded[1], 0, strpos($exploded[1], '.')));
$result[] = $substr;
}
return $result;
}
var_dump($test2);
For string input without linebreaks, a little parser could look like:
$stringExample2 = "The time is over. # its mean I'm need to die. Please help me. # Ghost. I am here alone. Sorry. # help yourself.";
var_dump(parseString3($stringExample2));
function parseString3($stringExample)
{
$result2 = [];
$startBlock = false;
$block = 0;
foreach (str_split($stringExample) as $char) {
if ($char === '#') { // Start block
$startBlock = true;
} else if ($startBlock && $char === '.') { // End block
$result2[$block] = trim($result2[$block]); // Remove unnecessary whitespace
$block++;
$startBlock = false;
} else if ($startBlock) { // Character to append to block
if (!isset($result2[$block])) { // We have to check if the block has been started already and if not, create it as an empty string because otherwise we would get a notice when trying to append our character to it.
$result2[$block] = '';
}
$result2[$block] .= $char;
}
}
return $result2;
}
If you use any of this code, please make sure to actually understand what is happening and use adequate variable names, these are just small example snippets.
All examples with their output can be found in the 3v4l link below
https://3v4l.org/k3TXM