Reputation: 967
How do you use a single character PHP Wildcard to make a String Replacement?
I need to make a string replacement in the following lines of code:
<img src="http://mydomain.com/image-1.jpg" alt="image 1"></a>
<img src="http://mydomain.com/image-2.jpg" alt="image 2"></a>
<img src="http://mydomain.com/image-3.jpg" alt="image 3"></a>
<img src="http://mydomain.com/image-4.jpg" alt="image 4"></a>
I want to replace the following string within all of the above lines:
alt="image *"></a>
where the * wildcard represents a number, with the following greater-than sign:
>
To yeild the following results:
<img src="http://mydomain.com/image-1.jpg">
<img src="http://mydomain.com/image-2.jpg">
<img src="http://mydomain.com/image-3.jpg">
<img src="http://mydomain.com/image-4.jpg">
If possible, I would like to do this using a single line of PHP code thus avoiding having to use a loop statement.
Thanks in advance.
Upvotes: 0
Views: 1574
Reputation: 16107
Regular Expressions or RegEx should do the trick nicely.
preg_replace('( alt="image [0-9]+"></a>)', '>', $text);
[]
means that any of the characters specified in the group can be matched as a wild-card.-
within the group means that the character group spans from a
to z
in our case 0-9
. *
at the end of the character group means that the group can repeat 0 or more times allowing us to define a number composed of multiple figures.Upvotes: 3