Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove all spaces and commas in a sentence

I'm working with data migration using Drupal 7. I am migrating some taxonomy terms and I wanted to know how to remove spaces and commas from a sentence.

If this is the sentence:

' this, is my sentence'

The desired result that I'm looking for:

'thisismysentence'

So far I have managed to do this:

$terms = explode(",", $row->np_cancer_type);
    foreach ($terms as $key => $value) {
      $terms[$key] = trim($value);
    }
var_dump($terms);

which only gives me the following result: 'this is my sentence' Anyone has a suggestion on how to achieve my desired result

like image 786
R2-D2's_Father Avatar asked Oct 26 '25 14:10

R2-D2's_Father


2 Answers

You can use one preg_replace call to do this:

$str = ' this, is my sentence';
$str = preg_replace('/[ ,]+/', '', $str);
//=> thisismysentence
like image 120
anubhava Avatar answered Oct 29 '25 06:10

anubhava


Just use str_replace():

$row->np_cancer_type = str_replace( array(' ',','), '', $row->np_cancer_type);

Example:

$str = ' this, is my sentence';
$str = str_replace( array(' ',','), '', $str);
echo $str; // thisismysentence
like image 23
Amal Murali Avatar answered Oct 29 '25 05:10

Amal Murali



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!