0

I am trying to learn regex and have a string, I want the beginning to be (not including)

.com/ 

and the end to be (not including)

">[tomato

I can make the basic regex ok, but it keeps including the tomato part in it, instead of ending just before it. So if I have

'sdf98uj3.com/sdjkh.sdf./sdf.sdf">[tomatoiosdf8uj3'

, then I want to return:

sdjkh.sdf./sdf.sdf

I am using preg_match in php. Any ideas?

1
  • If you are actually parsing URLs or HTML, regexes are not the best way to go (though they are pretty nifty for a lot of things and well worth learning). For URLs have a look at the PHP manual under parse_url or pathinfo. For HTML, have a look at SimpleXML. Commented Jan 31, 2011 at 17:30

2 Answers 2

1
preg_match('~\.com/(.*?)">\[tomato~', $str, $match);

$match[1] contains your string. The (.*?) is a capture group that captures every character between .com/ and ">[tomato.

http://www.regular-expressions.info/ is a good start for learning regular expressions.


Could also be solved without regex, using strpos(docs), strrpos(docs) and substr(docs):

$start = strpos($str, '.com/');
$end = strrpos($str, '">[tomato'); // or strpos to find the first occurance
$sub = substr($str, $start, $end-$start);
Sign up to request clarification or add additional context in comments.

Comments

0
preg_match('/(.*?)\.com/(.*?)">\[tomato(.*)/', $text, $matches);

echo $matches[2];

Comments

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.