示例字符串:
public interface Observer {
/**
* IF THIS METHOD IS NOT HERE SUBJECT WILL NOT BE ABLE TO CALL IT
* REFER TO OO BASICS - INHERITANCE
*/
void update(Subject subject);
}
public abstract class Subject {
// THE COMPLETE LOGIC HERE IS INDEPENDENT OF
// WHO THE CONCRETE SUBJECT IS.
// HENCE THIS IS A RIGHT PLACE FOR IT AS PER OO PRINCIPLES
// NOTE THAT THIS CLASS KNOWS ONLY ABOUT ABSTRACT OBSERVER
private Set<Observer> observers;
public void add(Observer o){/*...*/}
public void remove(Observer o){/*...*/}
protected void notifyAllObservers(){
for (Observer observer : observers) {
observer.update(this);
}
}
}
class ConcreteSubject extends Subject {
/**
* HERE THERE IS NO NEED TO KNOW THE CONCRETE OBSERVER-
* By DEFINITION OF THIS PATTERN.
* THE JOB HERE IS TO ONLY NOTIFY ALL OBSERVERS THAT "I HAVE CHANGED"
* ITS OBSERVER'S RESPONSIBILITY TO REACT IN PULL METHOD
*/
// Concrete Subject state
// Concrete Subject behavior
public void specificMethod(){
//... concrete class specific logic
}
}
class ConcreteObserver implements Observer{
@Override
public void update(Subject subject) {
/**
* OBSERVE HERE WE NEED TO TYPE CAST, WHICH LEADS TO VIOLATION OF
* OO PRINCIPLES. BUT WE GET BENEFIT OF LOOSELY COUPLED OBSERVERS
* AGAINST THIS EXTRA COST
* ITS SAFE TO VIOLATE HERE AS OBSERVER INSTANCES MAKE ONLY
* SENSE IN CONTEXT WITH SUBJECT AND WILL NEVER BE REUSED AS
* OBSERVERS IN UNRELATED CONTEXT.
*/
((ConcreteSubject)subject).specificMethod();
}
}
必须找到它们:
Here are sample apartment pictures {img="/path/photo1.jpg" alt="I am Photo Title"} and {img="/path/photo2.jpg" alt="I am Photo Title #2"} this...
如何在句子中找到这些图像链接?
答案 0 :(得分:0)
<?php
$string = "Here are sample apartment pictures {img='/path/photo1.jpg' alt='I am Photo Title'} and {img='/path/photo2.jpg' alt='I am Photo Title #2'} this...";
preg_match_all("/({([\w]+)[^}]*})(.*?)/", $string, $matches, PREG_SET_ORDER);
foreach ($matches as $val) {
echo "Variable Word In String: " . $val[1] . "<br>\n";
}
?>
答案 1 :(得分:0)
也可以通过爆炸来完成
我在这里爆炸&#34; {&#34;首先删除不以&#34开头的数组中的项目; img =&#34;。
然后我爆炸&#34;}&#34;删除右边的多余部分。
作为正则表达式的替代方案,并不是说它比正则表达式或strpos方法更好。
$str ='Here are sample apartment pictures {img="/path/photo1.jpg" alt="I am Photo Title"} and {img="/path/photo2.jpg" alt="I am Photo Title #2"} this...';
$arr = explode("{", $str);
Foreach($arr as $key => &$val){
if(substr($val,0,4) == "img="){
$val = "{". explode("}", $val)[0] . "}";
}else{
Unset($arr[$key]);
}
}
Var_dump($arr);