progNewbie
progNewbie

Reputation: 4822

Replace String with dynamicaly ending in php

I have a large String, containing "items1" and "items2" ... I don't know how much of these items exists. So I don't know until which number it is counting.

Now I need to replace all these parts of the String to "items"

Example:

asdfHelloBla"items2"HahaHabicht"items3"test => asdfHelloBla"items"HahaHabicht"items"test

Can anyone help me? Can I do this with regular expressions?

Upvotes: 1

Views: 60

Answers (1)

Mav
Mav

Reputation: 1190

You can do this using the following code:

<?php
    $string = 'asdfHelloBla"items2"HahaHabicht"items3"';
    $to_replace = array('"items1"', '"items2"', '"items3"');
    echo str_replace($to_replace, '"items"', $string);
?>

the str_replace function is used as follows:

str_replace(search, replace, subject);

It can accept an array as the 'search' argument and then replaces any of the matches with the 'replace' argument. You need to add all you want to replace in the $to_replace array that is in this case "item1", "item2" and so on and it should work fine. One more thing, you need to know the maximum limit till where the list goes. If you know the maximum limit, you can use a loop to replace '"item1"', '"item2"'.... with '"item{$n}"' Hope this helps :)

Upvotes: 1

Related Questions