Reputation: 1166
i have string like this pattern and i want to
income_statement@Other Income (Minority Interest)@9
remove numbers
remove special chars except @
replace spaces with underscores
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
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
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
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
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