0

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.

4
  • Get everything between s and /s BUT if they are both missing get everything? do they only appear once? Commented Aug 8, 2012 at 12:20
  • what about ABCsONLYONETAG? or JUST/sENDTAG? Commented Aug 8, 2012 at 12:43
  • @Waygood: Either both tags will be present or both will be absent. No other case Commented Aug 8, 2012 at 12:52
  • just needed clarifying because the straight preg_match answer would cover none, one or both. So its not correct for what you want. You need the pre-checking of @some-non-descript-user Commented Aug 8, 2012 at 13:04

2 Answers 2

1

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"
}
Sign up to request clarification or add additional context in comments.

6 Comments

And if they dont contain s and /s?
Getting Warning: preg_match(): Delimiter must not be alphanumeric or backslash
after using your updated code now I get this preg_match(): Internal pcre_fullinfo() error -3
@Waygood: you must check, if nothing was found, then use the entire string. That is better than make something like s?(.*?)(?:/s)?
Warning is removed now but the final output still contain s and /s can you help on this please
|
1

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;

1 Comment

+1 as this covers the fact that none or both TAGS need to be present.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.