Reputation: 832
I need to remove non-alphanumeric characters from between two strings using PHP.
Input:
name="K9 Mk. II"
built=2015.06.15
name="Queen Eliz. 3rd (HRH)"
Expected output:
name="K9MkII"
built=2015.06.15
name="QueenEliz3rdHRH"
My code:
$contents = file_get_contents("input.txt");
$contents = preg_replace('/name=\"[^A-Za-z0-9]\"/', "name=\"\\1\"", $contents);
Edit: it should only remove unwanted characters from between name=" and ". The line containing built=2015.06.15 should remain unchanged.
As always, your help is greatly appreciated.
WtS
Upvotes: 1
Views: 89
Reputation: 91430
$arr = array('name="K9 Mk. II"','name="Queen Eliz. 3rd (HRH)"');
foreach($arr as $str) {
$str = preg_replace_callback('/(?<=name=")([^"]+)(?=")/',
function ($m) {
return preg_replace("/\W+/", "", $m[1]);
},
$str);
echo $str,"\n";
}
Output:
name="K9MkII"
name="QueenEliz3rdHRH"
Upvotes: 2
Reputation: 34416
Here is the pattern you're looking for -
[^name=\w\"]
This excludes 'name=', word characters and whitespace. See it in action here
You can also use the return value instead of actual replacement -
$content = preg_replace('/[^name=\w\"]/', '$1', $content);
As the '$1'
will retain the quotes as you need them.
Upvotes: 3
Reputation: 1814
$output = preg_replace('/[^\da-z]/i', '', $InputString);
here i means case-insensitive.
$InputString is the input you provide.
$output contains the result we want
Upvotes: 0
Reputation: 4584
You can use PHP's preg_replace_callback() to first match the names by using: /name="([a-z0-9]+)"/i
and then calling a function removing the spaces in each match.
Upvotes: 0