2

I have what seems like quite a simple query. I have the following code in PHP:

$newThumb = str_replace('style="width:170px;"','',$nolinkThumb);

The problem that I have is that the number '170' can be any number therefore I would like my str_replace to reflect this. I have tried using:

$newThumb = str_replace('style="width:[0-9]px;"','',$nolinkThumb);

But this doesn't work. Any help would be greatly appreciated.

Thank you

3 Answers 3

9

You need to use regex, but [0-9] in regex means "the digits 0 to 9 repeated once".

What you're actually searching for is [0-9]+ which means "the digits 0 to 9 repeated one or more times":

$string = preg_replace('/style="width:[0-9]+px;"/', '', $string);
Sign up to request clarification or add additional context in comments.

Comments

3

Rather than using str_replace you need to use preg_replace to support regular expressions. More info can be found here: http://php.net/manual/en/function.preg-replace.php

So, for example, you could use:

$newThumb = preg_replace('/style="width:[0-9]+px;"/', '', $nolinkThumb);

Nevertheless, you should probably look at generating your HTML correctly, so that the style is kept separately (for example, in a CSS file) from the content and the business logic.

Comments

0
$newThumb = preg_replace('/style="width:[0-9]{1,}px;/', '', $nolinkThumb);

this regex also work. matching 1-X digits and replace the whole string

hope it helps

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.