Jump to content

Select a string using words


vanroojdotcom

Recommended Posts

I want to select a portion of text from some text stored in a database. Something along the lines of substr() but I can't determine - the start point or the file length. So I wondered if you could search for words and extract what's between?

 

So let's say the text is:

<img src="http://www.example.com/upload/2010/07/t_shutterstock_2674130.jpg">

 

 

I want to do something like

 

$start = 'upload'

$end = '.jpg'

 

 

echo = "/2010/07/t_shutterstock_2674130"

 

 

Is this possible?

Vanrooj

Link to comment
https://forums.phpfreaks.com/topic/207933-select-a-string-using-words/
Share on other sites

Yes this is possible using regular expressions.

 

http://php.net/manual/en/function.preg-match.php

 

<?php
// File name, could be a url
$str = '<img src="http://www.example.com/upload/2010/07/t_shutterstock_2674130.jpg">';

$pattern = '/upload(.*?).jpg/s';
$content = preg_match($pattern, $str, $matches);

print_r($matches);
?>

 

results in:

 

Array
(
    [0] => upload/2010/07/t_shutterstock_2674130.jpg
    [1] => /2010/07/t_shutterstock_2674130
)

BTW - if anybody is interested - I used this to pull a wordpress blog from the database to show just the images of the blog on the homepage - because the images are put into directories based on date (2007/07 etc) and not into a static folder - you need to extract the folder it's in to pinpoint the url. Using Imageizer to create thumbnails, inputting "wp-content/uploads/"  + the $matches and then a static  .jpg at the end of the source file you can place thumbnail images from your blog on the home page - and then link to the main article.

 

Works like a treat, thanks Wolphie.

 

PS: Worst forum post has to be Post 1:"Can you help me solve the world's problems? I need to reduce C02 to make the world a safer place."  Post 2 "No worries, I've solved it!" - with no explanation - baah!

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.