-1

I am trying to search the following text if it contains the specific link:

this my test text and it ontains the link to http://example.com/abc/files and http://example.com/def/files

I want that if I search for the link http://example.com/*/files, it should show me the text.

I tried this code but no result:

if (preg_match("/http://example.com/i", $content, $matches, PREG_OFFSET_CAPTURE))
{
     // Code Here
}  
reformed
  • 4,505
  • 11
  • 62
  • 88
Saqib
  • 41
  • 6

3 Answers3

2

You have two options:

  1. Escape /

    if (preg_match("/http:\/\/example.com/i", $content, $matches, PREG_OFFSET_CAPTURE)) {
    
  2. Use # instead of /

    if (preg_match("#http://example.com#i", $content, $matches, PREG_OFFSET_CAPTURE)) {
    

Also to use *, you need . in Regular Expression, so like this:

if (preg_match("#http://example.com/.*/files#i", $content, $matches, PREG_OFFSET_CAPTURE)) {

But be sure that simple wild card will match http://example.com/abc/files and http://example.com/def/files from your string. Since, you are trying to match any character(s) between http://example.com/ and /files. So, in this case, it finds the first instance and the last instance. Trying to match all in-between! To match only the first instance, use .*?. So you have to insert two extra symbols.

Thamilhan
  • 13,040
  • 5
  • 37
  • 59
1

you can do like this, don't use .* it match result as http://example.com/abc/files and http://example.com/def/files use [^/]+ or .*? instead

$content = 'this my test text and it ontains the link to http://example.com/abc/files and http://example.com/def/files';

if(preg_match("#http://example.com/[^/]+/files#i", $content, $matches)) {
    echo $matches[0];
    # http://example.com/abc/files
}
ewwink
  • 18,382
  • 2
  • 44
  • 54
0

Another suggestion other than using regular expressions is fnmatch() since that can do match checks on strings as well. Supports shell wildcards

http://php.net/fnmatch

if (fnmatch("*http://example.com/*/files*", $content)) {}

There may be limitations though such as a character limit (4096? Since it's normally used on file names) and not being supported in Windows.

georaldc
  • 1,880
  • 16
  • 24