Link to home
Start Free TrialLog in
Avatar of Dada44
Dada44Flag for Spain

asked on

Find string in a file and save it as a variable

Hi all,

I have
file_put_contents('temp.html', preg_replace('//', '', file_get_contents('http://www.mypage.com/')));

I want to find in temp.html the strings that start with http and end with .doc and save them into a variable/array.

How can I do that??

Thanks a lot in advance!
Avatar of kebabs
kebabs
Flag of Australia image

This finds http://anything.doc and stores a list in temp.html with each URL, one per line:

e.g.

Source document:
<a href="http://example.com/test1.doc">test1</a><a href="http://example.com/test2.doc">test2</a>

Result:
http://example.com/test1.doc
http://example.com/test2.doc
<?php
 
$contents = file_get_contents('http://example.com');
 
preg_match_all('~https?://.+\.doc~iU', $contents, $matches);
 
file_put_contents('temp.html', join("\n", $matches));

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of kebabs
kebabs
Flag of Australia image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of Dada44

ASKER

What I need is:
http://example.com/test1.doc
http://example.com/test2.doc
So I was following your first post.

Also I need
http://example.com/test1.doc
http://example.com/test2.doc
stored in a variable not in temp.html
Anyway temp.html comes out empty ..

Thanks in advance!!
Did you make the edit mentioned in the second post to the code in the first post?

Anyway, I think you want what I had in the second post, that one stores each URL in an array.
Avatar of Dada44

ASKER

Yes I chnaged in the first post what you told me to change in the second and I get an empty file.
If I use the second post the output is:
Array ( )
That's strange because I tested that code. I tested it again just then to make sure.

Are you sure there is something in temp.html to read from?

Can you run this to make sure that the contents to search in do in fact exist please:
<?php
 
echo file_get_contents('temp.html');

Open in new window

Avatar of Dada44

ASKER

Thanks pal, it was a typo bothering ...