How do I get substring from string which start with s
and end with /s
.
$text
can be in following formats
$text = "LowsABC/s";
$text = "sABC/sLow";
$text = "ABC";
how can I get ABC
, sometime it may happen that $text
does not contain s
and /s
just only ABC
, Still I want to get the ABC
.
The regular expression:
s(.*)/s
Or when you want to get a string of minimal length:
s(.*?)/s
And apply this res you can using preg_match
:
preg_match( '@s(.*)/s@', $text, $match );
var_dump( $match );
And now you must check, if something was found or not, and if not, then the result must be set to the entire string:
if (not $match) {
$match = $text;
}
Example of usage:
$ cat 1.php
<?
$text = "LowsABC/s";
preg_match( '@s(.*)/s@', $text, $match );
var_dump( $match );
?>
$ php 1.php
array(2) {
[0]=>
string(6) "sABC/s"
[1]=>
string(3) "ABC"
}
Might be trivial, but what about just using something like this (Regexs aren't always worth the trouble ;) ):
$text = (strpos($text,'s') !== false and strpos($text,'/s') !== false) ? preg_replace('/^.*s(.+)\/s.*$/','$1',$text) : $text;