how can I replace who string with certain beginning and ending, for example I have string:
abc........xyz

I want to replace this string with "this is a test", no matter what text in between, only "abc" and "xyz" are fixed.

abc123xyz-->this is a test
abcd1234xyz-->this is a test

any idea?

Dani AI

Generated

Both answers already posted are useful: pointed to a regex solution and offered a simple prefix/suffix check. Below are concise, practical options plus common pitfalls so the approach works reliably in real code.

For replacing any substring that starts with abc and ends with xyz use a non-greedy PCRE pattern so the smallest matching segment is replaced (dot does not match newlines by default, so add the s modifier when needed). Example:

$string = preg_replace('/abc.*?xyz/s', 'this is a test', $string);

To only replace when the whole string begins with abc and ends with xyz, anchor the pattern with ^ and $:

$string = preg_replace('/^abc.*?xyz$/s', 'this is a test', $string);

If the start/end markers are variables or might include regex metacharacters, escape them with preg_quote (second parameter is the chosen delimiter):

$start = preg_quote($start, '/');
$end   = preg_quote($end, '/');
$pattern = "/{$start}.*?{$end}/s";
$result = preg_replace($pattern, 'this is a test', $subject);

Notes and troubleshooting

  • Greedy vs non-greedy: use .*? (non-greedy) to avoid spanning multiple xyz occurrences.
  • Newlines: add s so . matches newline; add i for case-insensitive matching. See PCRE modifiers for details (pattern modifiers).
  • Performance: if only checking that the entire string starts with a fixed prefix and ends with a fixed suffix, simple string checks are faster than regex (this is the practical point behind ’s suggestion). For multibyte/UTF-8 strings, use mb_ functions or the u PCRE modifier.
  • References: PHP manual for preg_replace and preg_quote.

Recommended Answers

All 3 Replies

preg_replace()

Simple PHP should do it if you do not know regular expressions.

$string = "abcd123xyz";

if((substr($string,0,3)=="abc") && (substr($string,-3)=="xyz"))
{
  $string = "this is a test";
}

echo $string;

There are many ways, but i agree with top dogger, the above is the most simplest and works effectivly :D

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.