Christopher
Christopher

Reputation: 127

Remove spaces in one instance of variable?

I'm having trouble figuring out how to remove spaces, quote marks and periods in the first instance of $member['team_name'] (the one in the rel attribute) using str_replace.

foreach($members as $member) {
    echo '<div class="teamname" rel="' . $member['team_name'] . '">' . $member['team_name'] . '</div>';
}

Upvotes: 0

Views: 45

Answers (2)

bitfiddler
bitfiddler

Reputation: 2115

You could use preg_replace() something like this:

preg_replace("/(?:\s|\t|\'|\.|\"')+/", "", $member['team_name'], -1)

That will remove all spaces, tabs, dots and either quote mark

Upvotes: 0

calcinai
calcinai

Reputation: 2617

str_replace should do it fine -

echo '<div class="teamname" rel="' . str_replace(' ', '', $member['team_name']) . '">' . $member['team_name'] . '</div>';

That will work for spaces, you could use preg_replace to remove a general whitespace pattern.

EDIT (having seen your edit!):

The preg_replace pattern you're probably after would be something like

echo '<div class="teamname" rel="' . preg_replace('/[^a-z0-9]+/i', '', $member['team_name']) . '">' . $member['team_name'] . '</div>';`

This will replace any non-alphanumeric character. If you really only want spaces, quote marks and periods, you can go back to a str_replace with an array as the search argument - it will be faster.

str_replace(array(' ','"',"'",'.'), '', $member['team_name'])

Upvotes: 1

Related Questions