epool
epool

Reputation: 304

How to use regex to check if two characters exist in string no matter their location

I'm trying to convert csv imported numbers from (5.25) to -5.25 to be imported into a DB.

$CSV[] = 'abcd';
$CSV[] = '(5.25)';
foreach($CSV as $Record){
    if(preg_match_all("/[()]/", $Record, $output_array)){
        $Record = '-' . preg_replace("/[()]/", '', $Record);
    }
}

However, because i need to run this conversion on each record in the csv, and we don't know if the data in the column will be a number or some text, I need to only convert the string if both characters are present and wrapping the number.

Is this the proper way to use preg_match and preg_replace? It seems to be returning true to everything and essentially adding a dash "-" to every csv column.

Upvotes: 1

Views: 611

Answers (2)

Omkar T
Omkar T

Reputation: 883

(\s|^)⇢(\s|$)|(\s|^)⇠(\s|$)

Searches if character ⇢ or ⇠ exists

Upvotes: 0

benny
benny

Reputation: 315

you want something like this:

$CSV[] = 'abcd';
$CSV[] = '(5.25)';
$Record = array();
foreach($CSV as $value){
        $Record[] = preg_replace("/\(([^a-zA-Z]+?)\)/", '-$1', $value);
}
var_dump($Record);

Upvotes: 2

Related Questions