John Davidson

Remove part of a string in PHP

0 comments
Message:


How can I keep a part from a string:


$str = '../assets/uploads/8b3da36c4bce050/_hd/791df3a1355efd3.jpg';

I want to keep all after /_hd/.


I try with this but it keeps the hd/:


echo substr($str, strpos($str, '_hd/') + 1);
// hd/791df3a1355efd3.jpg

Thanks.



My Answer:
You can achieve this by adding the length of the substring you want to keep to the starting position. Here is the corrected code:

php
$str = '../assets/uploads/8b3da36c4bce050/_hd/791df3a1355efd3.jpg';
echo substr($str, strpos($str, '_hd/') + 4); // 791df3a1355efd3.jpg


This will output `791df3a1355efd3.jpg`, which is all the characters after `_hd/` in the original string.

Rate this post

3 of 5 based on 5940 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us