1

I want to search this string: "This is, mybigstring"

And search words could be: "is, big, mybigstring"

At the moment I'm using stristr which will find matches for all these words. However I do not want "big" to match.. Meaning that I won't allow substrings. How can I do this?

Update: I tried this out after reading your answers:

$testregxp = "\b(copenhagen|kobenhavn)\b";
$test = "Copenhagen, Denmark";
print preg_match($testregxp, strtolower($test));

But I can't seem to get it working..

1 Answer 1

3

You could use a regular expression for this. Depends if you want to find all instances of the word.

http://php.net/manual/en/function.preg-match.php

or

http://www.php.net/manual/en/function.preg-match-all.php to find all instances instead of just 1 match.

Also if you want to search all of them at the same time you can do that as well.

Something like

\bis\b should work. this should search for the actual word "is", so tis would not match, but your case "is," will even with that comma there.

to search for any of them at the same time you can do

\b(is|This|big)\b this will match is and This, but big won't be found.


Update

I'm not exactly sure what you want 100%, but you can just add the comma. IE: "/\b(copenhagen|kobenhavn)\b,/i" now if you want to include the comma in the search you can do, "/\b(copenhagen|kobenhavn)\b,?/i", so the comma is optional. If you did

\b(copenhagen|kobenhavn|denmark)\b,?

on

"Copenhagen, Denmark"

it will match

Copenhagen,

and

Denmark

Note the comma in Copenhagen, but the comma is optional in this case. So it will match the word with or without it.

Sign up to request clarification or add additional context in comments.

7 Comments

Thanks for your reply. I like this approach and I've made a test (see my edit). But I can't get it to work? My example outputs nothing..
@s0mmer one weird thing about php is you have to put in slashes. "/\b(copenhagen|kobenhavn)\b/"; try that instead. Oh i also noticed you have caps. You can do case-insensitive by add /i. So do, "/\b(copenhagen|kobenhavn)\b/i";
@Jared Farrish i am currently at work and they block a lot of websites. Unfortunately that is one site they do block now, so i can't see it.
@Matt: Not it works - thanks a lot! One more thing.. What if my string is "This is, still, mybigstring" and my search word is "This". This will match, however It would be more better if took the comma in consideration. Meaning the matches should only be: "This is", "still" and "mybigstring". Can this be done with regexp? I would really prefer not looping through..
@Jared Farrish - lol yea no, everything is blocked by default unless manually unblocked. Sucks :(, but im not sure what you mean by commas. If you want to go by each comma, yes you can use regex, but you can also just use explode to create an array of strings.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.