Scott B
Scott B

Reputation: 40177

String manipulation to remove tokens from string and assign the result to a variable?

Given the string variable in $widget_text...

$widget_text = '[widget_and-some-text]';

I need to do a string manipulation to end up with...

$widget_text_sanitized = 'and-some-text';

How?

ie, I thought this should work:

$widget_text = trim($widget_text,'[]');
$widget_text_sanitized = str_replace('widget_','',$widget_text);

Upvotes: 0

Views: 381

Answers (2)

Ruud
Ruud

Reputation: 3261

$widget_text_sanitised = substr($widget_text, 8, -1);

This will remove the first 8 and the last character from the string (no matter what characters they are).

Upvotes: 0

Pascal MARTIN
Pascal MARTIN

Reputation: 401142

Using a regular expression, you could have something like this :

$widget_text = '[widget_and-some-text]';

if (preg_match('/\[widget_([^\]]+)\]/', $widget_text, $matches)) {
    var_dump($matches[1]);
}

Which would get you :

string 'and-some-text' (length=13)

Upvotes: 2

Related Questions