Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Grab value from string using specific pattern

I have the data like this.

<h1><img alt="" src="http://localhost:8000/images/synx_1644770022.jpg" style="float:left; height:150px; width:158px" />Synx Tech</h1>

<p>Here we go again testing to upload sum images</p>

<p>&nbsp;</p>

<p><img alt="" src="http://localhost:8000/images/neki_1644770127.jpg" style="float:right; height:150px; width:150px" />TESTING UPLOAD SUM IMAGES BUT ON RIGHT SIDE IS NEKI!!!!</p>

<p><a href="https://engdropfen.com">Click this link</a></p>

I want to grab all images name and directory like this : images/thenameofimage.jpg.
I already tried using regex like this

$src =  $article->body;
preg_match_all('~src="([^"]+)~', $src, $matches);
print_r($matches[1]);

It success and show the whole link that contain in $src variable and the result is like this:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Array ( [0] => http://localhost:8000/images/synx_1644770022.jpg [1] => http://localhost:8000/images/neki_1644770127.jpg )

In here I just want to grab text after http://localhost:8000/. I want to grab dynamically, I mean when I changed my domain of website I still can grab the images/thenameofimage.jpg after my domain name. I confused how to grab it, anyone have the solution? Thanks before.

>Solution :

I would not recommend using DOMDocument unless you have to manipulate the DOM, as it performs worse than preg_match in every test I have seen.

To grap the image path from the array you could use parse_url in a foreach loop:

$image_path = parse_url( $image_url, PHP_URL_PATH );
// Output example: /images/synx_1644770022.jpg
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading