Page 1 of 1

Using OR/AND in preg_replace ?

Posted: Thu Jul 08, 2010 8:23 am
by dominod
Hi

I want to use two lines for on string in preg_replace..

I want the following two codes to work:

Code: Select all

$shop = preg_replace('/:([a-zA-Z0-9]*(\s){0,1})/','',$search);

Code: Select all

$shop = preg_replace('/: ([a-zA-Z0-9]*(\s){0,1})/','',$search);
The difference between them is that the second one got space between ":" and "([a.."

The problem I am trying to solve is this..

When I use the first line of code and type in "keyword: wordkey" it echo "keywordwordkey" instead of "keyword" as it shuld and does when I enter "keyword:wordkey" (without the space).

When I am using the other line of code and type in "keyword:wordkey" it echo "keyword:wordkey" and not "keyword" is it shuld and does when I enter "keyword: wordkey" (with the space).

What I want is that it echos "keyword" no matter if there is a space there or not ..

Does anyone know how to fix this?

Thanks in advance :)

Re: Using OR/AND in preg_replace ?

Posted: Thu Jul 08, 2010 8:29 am
by Weirdan
Mark the space as optional using the ? quantifier:

Code: Select all

/keyword: ?something/ // matches 'keyword:something' and 'keyword: something'
Or, better yet, allow any number of spaces on either side of the colon:

Code: Select all

/keyword\s*:\s*something/  // matches 'keyword:something' and 'keyword: something', but also 'keyword     :      something'

Re: Using OR/AND in preg_replace ?

Posted: Thu Jul 08, 2010 8:43 am
by dominod
Okey that solved that problem .. But there is another thing ..

If I write "keyword:wordkey word2 word1" it leaves me with "keywordword2word1"

What I want is to only echo the word before ":" ..

Thanks alot for helping me with the other issue though :mrgreen:

Re: Using OR/AND in preg_replace ?

Posted: Thu Jul 08, 2010 9:41 am
by Weirdan
it seems it's easier to solve with matching instead of replacing:

Code: Select all

preg_match_all('/(\w+)\s*:/', $search, $keywords);
$shop = join(' ', $keywords[1]);

Re: Using OR/AND in preg_replace ?

Posted: Thu Jul 08, 2010 10:32 am
by dominod
Thanks alot Weirdan :)

U really made my day :D