我有字符串
$string = '<b>My name is "David"</b>. My girlfriend is <b>"Tessi"</b> This text is only example. I want to get only words "between two quotes".';`
我需要用自定义HTML div替换"
内的所有内容:
<div class="name_replaced">HERE_PUT_WORD_FROM_QUOTES</div>
所以,最后字符串必须是:
$string = '<b>My name is <div class="name_replaced">David</div></b>. My girlfriend is <b><div class="name_replaced">Tessi</div></b> This text is only example. I want to get only words <div class="name_replaced">between two quotes</div>.';`
如何?
答案 0 :(得分:4)
您使用preg_replace
$string = '<b>My name is "David"</b>. My girlfriend is <b>"Tessi"</b> This text is only example. I want to get only words "between two quotes".';
$string = preg_replace('/"(.*?)"/i', '<div class="name_replaced">\1</div>', $string);
函数代码
urlfetch
答案 1 :(得分:1)
使用简单的preg_replace()
可以解决问题。下面的代码片段显示了如何:
<?php
$string = '<b>My name is "David"</b>. My girlfriend is <b>"Tessi"</b> This text is only example. I want to get only words "between two quotes".';
$wordsBW2Quotes = preg_replace("#([\"'])([\w\s]+)([\"'])#", "$2", $string);
var_dump($string);
var_dump($wordsBW2Quotes);
// FIRST VAR_DUMP PRODUCES:
// '<b>My name is "David"</b>. My girlfriend is <b>"Tessi"</b> This text is only example. I want to get only words "between two quotes".' (length=132)
// SECOND VAR_DUMP PRODUCES:
// '<b>My name is David</b>. My girlfriend is <b>Tessi</b> This text is only example. I want to get only words between two quotes.' (length=126)
测试Here。
答案 2 :(得分:0)
$string = '<b>My name is "David"</b>. My girlfriend is <b>"Tessi"</b> This text is only example. I want to get only words "between two quotes".';`
$newString = str_replace('"', '</div>', str_replace('"', '<div class="name_replaced">', $string));