Author Topic: help with a string.  (Read 2235 times)

mbenson

  • New Member
  • *
  • Posts: 4
  • Karma: +0/-0
    • View Profile
help with a string.
« on: May 22, 2009, 02:57:15 PM »
Wow, how the board has changed..

I used to come here all of the time, and then couldn't, due to the type of work I did.

Some of you may remember me, but not likely.

I am going to be trying to come back as often as possible, too.

I have since my last visit, I have, with a partner, just launched a site called windsorinsider.ca. It is half news site, and half business listing site. We are keeping everything local to our community. We are also going to be competing with the local newspaper here. That's the fun part.

Ckeck it out.

But the real reason I am here today, is to see about getting some help with a string of characters.

I am storing articles in a table, and the story feild in Mysql stores all of the html for images.

I am trying to get the img tag out of the data, and even manipulate that further.

If I wanted to get :

<img height="165" width="220" class="imgcaption" title="A CUPE sign blows in the wind at Malden Park while negotiations are taking place with city officials. Photo by: Justin Saunders" src="/images/articles/82/DSCF4122[1](1).jpg" alt="" />

out of a the story string of text, then remove the height,  width and class elements, and copy the title out and store that in a variable. what would you suggest using?

I have been working with strings, but can't get this one.

Any help is much appreciated.

Thanks guys, and see you soon.

PHP Coder

  • Expert PHP Helper
  • Senior Member
  • *****
  • Posts: 130
  • Karma: +0/-0
    • View Profile
    • PHP coder
Re: help with a string.
« Reply #1 on: May 20, 2010, 03:20:46 AM »
There are actually two tasks, not one - first is to eliminate attributes what you mentioned, second is to extract title and put it in a variable.

For the first task, this regular expression will make replacements what you need for every matched entry in  the content (though the order of the attributes is important):

PHP Code: [Select]

$new_content 
preg_replace("~(<[\s]*?img[\s]+)(height=\"[\d]+\"[\s]*)?(width=\"[\d]+\"[\s]*)?(class=\"[^\"]*\"[\s]*)?(title=\"[^\"]*\"[\s]+)?(src=\"[^\"]*\"[\s]*)?(alt=\"[^\"]*\"[\s]*)?([\s]+/>)~i","\\1\\5\\6\\8",$content);


As for extracting title to a variable, you can use preg_match_all to find all image titles in the content:

PHP Code: [Select]

if(preg_match_all("~<[\s]*?img[\s]+[^>]*title=\"([^\"]*)\"[^>]*/>~i",$content,$matches)){
  
print_r($matches[1]);
}

PHP coder for hire