Using OR/AND in preg_replace ?

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
dominod
Forum Commoner
Posts: 75
Joined: Wed Jun 30, 2010 7:18 am

Using OR/AND in preg_replace ?

Post 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 :)
User avatar
Weirdan
Moderator
Posts: 5978
Joined: Mon Nov 03, 2003 6:13 pm
Location: Odessa, Ukraine

Re: Using OR/AND in preg_replace ?

Post 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'
dominod
Forum Commoner
Posts: 75
Joined: Wed Jun 30, 2010 7:18 am

Re: Using OR/AND in preg_replace ?

Post 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:
User avatar
Weirdan
Moderator
Posts: 5978
Joined: Mon Nov 03, 2003 6:13 pm
Location: Odessa, Ukraine

Re: Using OR/AND in preg_replace ?

Post 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]);
dominod
Forum Commoner
Posts: 75
Joined: Wed Jun 30, 2010 7:18 am

Re: Using OR/AND in preg_replace ?

Post by dominod »

Thanks alot Weirdan :)

U really made my day :D
Post Reply