user1080247
user1080247

Reputation: 1166

how to remove spaces and numbers without at spcial char?

i have string like this pattern and i want to

income_statement@Other Income (Minority Interest)@9

i do something like this but it was not work yet

$spaces = str_replace(' ', '_', $key);
 echo  $numbers = preg_replace("/[^a-zA-Z]/", "_", $spaces);

Upvotes: 0

Views: 71

Answers (4)

Giuseppe Ricupero
Giuseppe Ricupero

Reputation: 6272

FIRST STEP (remove numbers, every non letter, note that this include the underscore _ too but not simple whitespace)

$re = "/(?:[^a-z@ ]|\d)/i";
$str = "income_statement@Other Income (Minority Interest)@9"; 
$subst = ""; 

$result = preg_replace($re, $subst, $str);

Output:

incomestatement@Other Income Minority Interest@

SECOND STEP (sub spaces with underscore _)

$re = "/\s+/";
$str = "incomestatement@Other Income Minority Interest@";
$subst = "_"; 

$result = preg_replace($re, $subst, $str);

Output:

incomestatement@Other_Income_Minority_Interest@

COMPACT VERSION

$str = "income_statement@Other Income (Minority Interest)@9";
$stripped = preg_replace("/(?:[^a-z@ ]|\d)/i", "", $str);
$result = preg_replace("/\s+/", "_", $stripped);

Upvotes: 1

DLevsha
DLevsha

Reputation: 136

$data = preg_replace("/[^a-zA-Z@ ]+/", '', $data); // remove all except letters and @ (if you want keep \n and \t just add it in pattern)
$data = str_replace(' ', '_', $data);  

Upvotes: 1

Mike
Mike

Reputation: 1231

You can make it done with two preg_replace and one str_replace :

$str = 'income_statement@Other Income (Minority Interest)@9';
 // Change space to underscore
 $str = str_replace(' ','_',$str);
 // Remove all numbers
$str = preg_replace('/[\d]+/','',$str);
// Remove all characters except words and @ in UTF-8 mode
$str = preg_replace('/[^\w@]+/u','',$str);

// Print it out
echo $str;

Upvotes: 1

tino.codes
tino.codes

Reputation: 1507

<?php
// this should work and replace all spaces with underscores
$spaces = str_replace(' ', '_', $key);

// you have to add the @ and the underscores in your expression
// and replace it with an empty string
echo  $numbers = preg_replace('/[^a-zA-Z@_]/', '', $spaces);

Upvotes: 1

Related Questions