Hi,

A little stuck here - i have a file containing info like this:
Name: Some Name Email: some@email.com
I'm using file_get_contents to read the file and then i want to get the name. I have it like

preg_match('/Name:(.*?) Email:/',$filecont,$name);

however it returns nothing.
Maybe anyone has an idea how to make this work?

Thanks.

$name is an array, you should use $name[1] to get just the name part.

Hi,

A little stuck here - i have a file containing info like this:
Name: Some Name Email: some@email.com
I'm using file_get_contents to read the file and then i want to get the name. I have it like

preg_match('/Name:(.*?) Email:/',$filecont,$name);

however it returns nothing.
Maybe anyone has an idea how to make this work?

Thanks.

Form PHP Manual:
preg_match() returns the number of times pattern matches. That will be either 0 times (no match) or 1 time because preg_match() will stop searching after the first match. preg_match_all() on the contrary will continue until it reaches the end of subject. preg_match() returns FALSE if an error occurred.

preg_match_all('/Name:(.*?) Email:/',$filecont,$name);

When checking the $name array, it contains 2 indexes (0 and 1), and both of them is another empty array. Still no name found.

I tried the statement with a string and it works fine using the format you indicated. Perhaps the file isn't being read in properly?

This works, for example:

<?php

$filecont ='Name: Some Name 1 Email: some@email.com
Name: Some Name 2 Email: some@email.com
Name: Some Name 3 Email: some@email.com
Name: Some Name 4 Email: some@email.com
Name: Some Name 5 Email: some@email.com
Name: Some Name 6 Email: some@email.com
';
preg_match('/Name:(.*?) Email:/',$filecont,$names);
print_r($names);

preg_match_all('/Name:(.*?) Email:/',$filecont,$names);
print_r($names);
?>

I got it working. It was actually the newline character (\n), which was in the file, but was not a part of the regular expression. Removing the newlines before preg_match works fine.

Thanks

Solved

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.