Jump to content

Preg match all question


factoring2117

Recommended Posts

Hi,

 

I have been working at this for days and can't seem to output the right info.

 

Here is the string I am working with.

 

$str = "<land><id>0</id><image_url>http://example.com</image_url><num_owned>0</num_owned><cost>4500</cost><name>Vacant Lot</name><income>$100</income></land>

<land><id>1</id><image_url>http://www.example.com</image_url><num_owned>0</num_owned><cost>45000</cost><name>Empty Storefront</name><income>$300</income></land>

<land><id>2</id>http://www.example.com</image_url><num_owned>0</num_owned><cost>900000</cost><name>Plaza</name><income>$2,000</income></land>";

 

I need to extract id, image_url, num_owned, cost, name, and income for each of these three.

 

Here is my code so far:

 

$preg = "#<land><id>(.*?)</id><image_url>(.*?)</image_url><num_owned>(.*?)</num_owned><cost>(.*?)</cost><name>(.*?)</name><income>(.*?)</income></land>#i";

if(preg_match_all($preg,$str,$match)) {
        	foreach($match as $val) {
        		echo $val[1];
        	}
        }

 

I get the following when I run the script (inside the source code):

 

<land><id>1</id><image_url>http://www.example.com</image_url><num_owned>0</num_owned><cost>45000</cost><name>Empty Storefront</name><income>$300</income></land>1http://www.example.com045000Empty Storefront$300

 

Here are the problems that I am having.

 

1) I need to be able to use the image, income, cost, name, for each one of the 3 land strings. I understand that if I make the $val[1] variable $val[2] I will output the second land string, but I need to use each one of the image, income, cost, name and income variables. How do I do this?

 

2) There are more than just 3 land strings so I need a regex string that will satisfy that demand.

 

My ultimate goal would be to create a calculator to calculate which land is the best value to purchase.

 

So in this particular case I need to take the cost/income= best_value

 

 

 

I appreciate all your help before hand.

 

Link to comment
https://forums.phpfreaks.com/topic/155561-preg-match-all-question/
Share on other sites

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.