Black
Black

Reputation: 20402

trim does not remove letters from string

I tried to use trim to remove the letter 'W' and 'l' from my string $text. But instead of the output `Hao et" i get "Hallo Welt", so trim did not worked.

<?php
        $text = "Hallo Welt";
        $text = trim($text, 'lW');

        echo "<p>Text = ".$text."</p>";
?>

Output: Hallo Welt

I informed myselve here.

Upvotes: 0

Views: 157

Answers (5)

Abhishek Sharma
Abhishek Sharma

Reputation: 6661

use str_replace like that :-

str_replace('W','',$text)

or try this :-

str_replace("W","",str_replace("l","",$text))

str_replace(find,replace,string,count)

Upvotes: 1

Brane
Brane

Reputation: 3339

You can use array for archiving that, where you can define all of the letters that you want to remove. Something like this:

$vowels = array("a", "e", "i", "o", "u", "A", "E", "I", "O", "U");
$onlyconsonants = str_replace($vowels, "", "Hello World of PHP");

Upvotes: 1

Marius Lazin
Marius Lazin

Reputation: 76

Check better the definition of the function, it trims only from the beginning and end of a string: "Strip whitespace (or other characters) from the beginning and end of a string".

You could try using preg_replace

Upvotes: 1

Tanuel Mategi
Tanuel Mategi

Reputation: 1283

trim works differently. it only removes letters from the side of the string.

$string = trim("asd Hallo asd", "asd");

will give you " Hallo "

what you need is str_replace:

<?php
    $text = "Hallo Welt";
    $text = str_replace("l","",$text);
    $text = str_replace("W","",$text);

    echo "<p>Text = ".$text."</p>";
?>

also works with arrays:

<?php
    $text = "Hallo Welt";
    $search = array("l","W");
    $text = str_replace($search,"",$text);

    echo "<p>Text = ".$text."</p>";
?>

Upvotes: 4

pistou
pistou

Reputation: 2867

trim only removes characters at the beginning and the end of your String.

If you want to remove every occurence of your letters, use str_replace

Upvotes: 0

Related Questions