# Regex not working on extracting URL from text

**URL:** <https://www.phphelp.com/t/regex-not-working-on-extracting-url-from-text/19121>\
**Category:** General PHP Help\
**Created:** [December 12, 2012, 8:03pm UTC](https://www.phphelp.com/t/regex-not-working-on-extracting-url-from-text/19121 "2012-12-12T20:03:25Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![kencook](https://www.phphelp.com/letter_avatar_proxy/v4/letter/k/8e7dd6/32.png) [@kencook](https://www.phphelp.com/u/kencook)\
**Post date:** [December 12, 2012, 8:03pm UTC](https://www.phphelp.com/t/regex-not-working-on-extracting-url-from-text/19121/1 "2012-12-12T20:03:25Z")

</div>

Eventually I want to end up with the 9bbfc150 part of the URL (not the iframe id in case the user only pastes the URL into the form). Currently finding 0 URLs.

[php]\<?php

$url\_string = ‘’;

preg\_match\_all(’#(www.|https?://){?}[a-zA-Z0-9]{2,254}.[a-zA-Z0-9]{2,4}(\S\*)#i’,$url\_string,$a);

$count = count($a[1]);  
echo “URLs = " .$count.”

";  
for ($row = 0; $row \< $count ; $row++) {  
echo $a[1]["$row"]."  
";

?\>[/php]

---

<div class="post-metadata">

**Author:** ![m11](https://www.phphelp.com/letter_avatar_proxy/v4/letter/m/85f322/32.png) [@m11](https://www.phphelp.com/u/m11)\
**Post date:** [December 12, 2012, 8:45pm UTC](https://www.phphelp.com/t/regex-not-working-on-extracting-url-from-text/19121/2 "2012-12-12T20:45:35Z")

</div>

The regex isn’t valid. I’m not sure why you have # at the beginning and end but they should be forward slashes.

I also don’t know what {?} is supposed to do.

With these two errors fixed, you are only matching the following string:

```auto
/embed/9bbfc150/?f=1&autoplay=0&player=full&secret=754743&loop=0&nologo=0&hd=0"></iframe>
```

Also, why the loop when there is only 1 URL in the string?

---

<div class="post-metadata">

**Author:** ![m11](https://www.phphelp.com/letter_avatar_proxy/v4/letter/m/85f322/32.png) [@m11](https://www.phphelp.com/u/m11)\
**Post date:** [December 12, 2012, 9:31pm UTC](https://www.phphelp.com/t/regex-not-working-on-extracting-url-from-text/19121/3 "2012-12-12T21:31:50Z")

</div>

Here are a couple options…

You could extract the URL from the src value then extract the ID from that

[php]preg\_match\_all(’/src="(.\*?)"/i’, $url\_string, $a);[/php]

You could extract the ID if the URL is always the same /embed/ID

[php]preg\_match\_all(’/src=".\*?/embed/([^/]+)/i’, $url\_string, $a);[/php]

This is the same method but also contains the domain validation from your original regex

[php]preg\_match\_all(’/(www.|https?://)[a-zA-Z0-9]{2,254}.[a-zA-Z0-9]{2,4}/embed/([^/]+)/i’, $url\_string, $a);[/php]
