Sammy
Sammy

Reputation: 967

How do you use a single character PHP Wildcard to make a String Replacement?

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

Answers (1)

Mihai Stancu
Mihai Stancu

Reputation: 16107

Regular Expressions or RegEx should do the trick nicely.

preg_replace('( alt="image [0-9]+"></a>)', '>', $text);
  • In RegEx the construct of character groups [] means that any of the characters specified in the group can be matched as a wild-card.
  • Using a dash - within the group means that the character group spans from a to z in our case 0-9.
  • Using an asterisk * 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.
  • Using a plus sign instead of an asterisk means that the group can repeat 1 or more times (this might be better suited here since you want to match a number not an empty slot).

Upvotes: 3

Related Questions