0

I have to use a regular expression to get the text after the last "/" and before "_completed" string.

For example if my input is :

http://localhost/project-1/uploaded_images/output//11-03-2013+11-09-2013/Brian_Brown_completed.jpg 

I need to output "Brian Brown" is that possible with preg_match? Unfortunately I could not figure it out! How about the javascript is it possible there too?

If you need more clarification, please let me know!

EDITED:

Please note that in output I dont have underscore anymore!

Many thanks in advance,

5
  • 2
    Yes, it's possible in both PHP and Javascript. What have you tried that didn't work? Commented Nov 11, 2013 at 16:45
  • I was trying preg_match but I dont know how to pass the pattern! Commented Nov 11, 2013 at 16:47
  • The pattern is passed as the first argument. Commented Nov 11, 2013 at 16:47
  • But I didnt deserve minus score! :( Commented Nov 11, 2013 at 16:51
  • I didn't downvote, but I'll bet it was because your question looks like you've made no attempt to solve the problem yourself. There are thousands of questions here with examples of using preg_match. Commented Nov 11, 2013 at 16:54

5 Answers 5

1

With JavaScript

Fiddle DEMO

var str = 'http://localhost/project-1/uploaded_images/output//11-03-2013+11-09-2013/Brian_Brown_completed.jpg ';
console.log(str.substring(str.lastIndexOf("/")+1).split('_completed')[0]);


Reference

.lastindexof()

.split()

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

1 Comment

Thanks you solved my problem; I just added split('')[0] at the very end to get the first part and then split('')[1] for the second part to get rid of "_" in between Thanks
1

In case a non-regexp solution is acceptable:

<?php
$url = 'http://localhost/project-1/uploaded_images/output//11-03-2013+11-09-2013/Brian_Brown_completed.jpg';
$test = basename($url, '_completed.jpg');

Comments

0
if (preg_match('~([^/]+)_completed\.jpg$~', $url, $match)) {
    echo $match[1];
}

Comments

0

PHP:

preg_match('#.*/(.*)_completed\.jpg$#', $input, $match); // Find the name
$name = str_replace('_', ' ', $match[1]); // Convert underscores to spaces

Javascript:

name = /.*\/(.*)_completed\.jpg$/.exec(input)[1].replace(/_/, ' ');

Comments

0

This should do:

$s = str_replace ("_", " ", substr ( $s, strrpos($s, "/")+1, strrpos($s, "_completed")-strrpos($s, "/")-1 )) ;

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.