This is an example of a string: abcde123#ijklmn0pq
In that string I need to print out only the numbers (the 123
sequence), and remove the letters (from both left and right) and the hashtag (#
) to be removed as well.
The hashtag (#
) is always included in the string.
The hashtag (#
) is always positioned to the right of the characters that need to be printed;
The hashtag (#
) is always positioned to the left of the characters that need to be removed;
Therefore, the hashtag (#
) can be used as a guide to remove the letters from the Right
The number of characters in the beginning is always equal to 5 (constant) (to be removed);
The number of characters in the middle is always different (variable) (to be printed);
The number of characters in the right is always different (variable) (to be removed);
Here's another string example, similar to the first one: !!@@$IMPORTANT#=-=whatever
The characters that need to be printed are the word "IMPORTANT
"
As with the first example, what's on the left side of the hashtag (#) needs to be printed, but it's important to print only the "IMPORTANT
" word, without the special characters "!!@@$".
$myString = '!!@@$IMPORTANT#=-=whatever';
$result = substr($myString, 5, -1);
$pos = strpos($result, '#');
$result = substr($result, 0, $pos);
echo $result;
Ill give a stab at this. seems pretty simple.
function choppy($choppy) {
$nstr = substr($choppy, 5,strlen($choppy)); //chop first 5
$pos = strpos($nstr, "#"); //Find the position of the hash tag
return substr($nstr, 0, $pos); //we only need the stuff before it...
}
echo choppy('!!@@$IMPORTANT#=-=whatever');
echo "
";
echo choppy('abcde123#ijklmn0pq');
Result
C:\Users\developer\Desktop>php test.php
IMPORTANT
123
The other answers are good but if you need a one-liner for your homework:
$str = '!!@@$IMPORTANT#=-=whatever';
echo substr($str, 5, strpos($str, '#')-5); //IMPORTANT
You can use regexes with preg_replace()
;
Assuming that the string you need to process is stored in $string
:
preg_replace('^.{5}(.*)#.*$', '$1', $string);
https://www.regex101.com/r/hA8lY7/1
First pattern explanation:
^.{5}
: matches any 5 character after the start of $string
(.*)
: matches any N character after (1) before the first occurence of #
(first capturing-group)#.*$
: matches #
and any N character after (2) before the end of $string
Second pattern explanation:
$1
: replaces $string
with the first capturing-group matched in the first pattern