0

The string

abc/def/*

or

abc/def/*/xyz

How can I use preg_replace_callback to replace everything after /* with a certain string?

Like

abc/def/replacement

2
  • I don't know, but i guess you don't want to manualy chech for present of "/*", then cut the string to the position of "/*" and then add the replacement? Commented Feb 21, 2012 at 20:02
  • So in both examples, the result will be the same (the value you have under "Like") ? Commented Feb 21, 2012 at 20:33

2 Answers 2

1
<?php
$string = "abc/dc/*bla/foo";

$string = preg_replace_callback(
    '~/\*.*~',
    create_function(
      '$match',
      'return "/replacement";'
    ),
    $string
);

var_dump($string);
?>

output

string 'abc/dc/replacement' (length=19)
Sign up to request clarification or add additional context in comments.

Comments

1

Something like this should work:

$text = "abc/def/*/xyz";
function rep($matches)
{
  return "/replacement";
}
echo preg_replace_callback("|/\*.*|", "rep", $text);

Do you really need to use preg_replace_callback though? Here is an equivalent version with preg_replace:

$text = "abc/def/*/xyz";
echo preg_replace("|/\*.*|", "/replacement", $text);

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.