php用数组中的值替换所有字符串出现

时间:2017-02-13 09:15:21

标签: php arrays

我有一个包含图片ID的字符串和一个数组,其中包含旧图片ID的键和新图片ID的值。

我需要在内容中搜索旧内容并替换为新内容。

我已经完成了这个

<?php

$string = 'Lorem ipsum dolor sit amet, image="150" consectetur adipisicing elit. Porro voluptatibus omnis nulla quis mollitia dicta quasi voluptatum totam,
labore doloremque ea fugit consectetur, itaque, ab et odio, est iusto recusandae suscipit? Dignissimos veniam recusandae, magnam, dolor omnis, image="6"
 eveniet laboriosam quas culpa voluptate at officia in natus repellendus assumenda beatae illo repudiandae earum necessitatibus fugit, 
quo error. <span style="padding-top:150px">Esse minima</span>, aut architecto, doloribus quos veritatis reprehenderit.
 Temporibus vitae voluptatibus ea ad similique perspiciatis sed doloribus explicabo error asperiores ab, id aspernatur image="235" eum ducimus magni rerum veniam voluptates, ipsum voluptatum repudiandae dolorum quisquam voluptatem. 
Doloribus nulla voluptate architecto ipsam sed voluptas, maiores rem sequi eos voluptatum iusto rerum odio sapiente sunt minima, image="65" consequuntur aliquid dolor impedit hic. Beatae perspiciatis, incidunt necessitatibus
 voluptas earum cumque, in asperiores id ipsum ducimus veritatis laboriosam eveniet ipsa accusamus! Nulla quasi porro sunt suscipit quibusdam velit
 itaque, voluptates, soluta quaerat consectetur eos doloribus, fugiat quisquam. Quos, ad, dolorum.
';

$array = array(
    '150' => 4025,
    '6'   => 4026,
    '235' => 4027,
    '65'  => 4028,
);

preg_match_all( '/image=\"(\d+)\"/', $string, $matches_image );

if ( '' !== $matches_image[1] && ! empty( $matches_image[1] ) ) {
    foreach ( $matches_image[1] as $key => $matched_image_id ) {
        if ( array_key_exists( $matched_image_id, $array ) ) {
            $string = str_replace( $matched_image_id, $array[ $matched_image_id ], $string );
        }
    }
}

但是,如果您print_r $string,您会注意到它会替换每次出现的ID(应该如此),但这也会替换范围中的顶部填充(对于image='150'实例)。所以最后我得到4025px的顶部填充,这是不好的:D

我在考虑首先使用正确的ID替换找到整个匹配模式(from pyspark.sql import SQLContext, Row from pyspark.ml.feature import CountVectorizer from pyspark.mllib.clustering import LDA, LDAModel from pyspark.mllib.linalg import Vector, Vectors path = "sample_text_LDA.txt" data = sc.textFile(path).zipWithIndex().map(lambda (words,idd): Row(idd= idd, words = words.split(" "))) docDF = spark.createDataFrame(data) Vector = CountVectorizer(inputCol="words", outputCol="vectors") model = Vector.fit(docDF) result = model.transform(docDF) corpus = result.select("idd", "vectors").rdd.map(lambda (x,y): [x,Vectors.fromML(y)]).cache() # Cluster the documents into three topics using LDA ldaModel = LDA.train(corpus, k=3,maxIterations=100,optimizer='online') topics = ldaModel.topicsMatrix() vocabArray = model.vocabulary wordNumbers = 10 # number of words per topic topicIndices = sc.parallelize(ldaModel.describeTopics(maxTermsPerTopic = wordNumbers)) def topic_render(topic): # specify vector id of words to actual words terms = topic[0] result = [] for i in range(wordNumbers): term = vocabArray[terms[i]] result.append(term) return result topics_final = topicIndices.map(lambda topic: topic_render(topic)).collect() for topic in range(len(topics_final)): print ("Topic" + str(topic) + ":") for term in topics_final[topic]: print (term) print ('\n') )的匹配数组,然后匹配内容中替换的值。

但是我被卡住了。

3 个答案:

答案 0 :(得分:3)

您的代码存在的问题是,str_replace()将替换字符串中$matched_image_id的任何实例,而不仅仅是image='...'字符串中的str_replace("image=\"$matched_image_id\"", "image=\"{$array[$matched_image_id]}\"", $string); 实例。你需要使它更具体:

preg_replace_callback()

但是您可以使用$string = preg_replace_callback('/image="(\d+)"/', function($match) use ($array) { return "image=\"{$array[$match[1]]}\""; }, $string); 完成所有操作,因此您只能替换与正则表达式匹配的部分。回调函数可以查找数组中ID的替换。

class User(Base):
    __tablename__ = 'user'
    id = Column(Integer, primary_key=True)

    def __init(self,first_name,last_name):
         self.first_name = first_name
         self.last_name = last_name 

    _fullname = Column("fullname", String)

    @property
    def fullname(self):
        return self.first_name + self.last_name

    @fullname.setter
    def set_fullname(self, fullname):
         self.first_name = fullname[0:2]
         self.last_name = fullname[2:]

答案 1 :(得分:0)

丑陋,但它有效

$string = 'Lorem ipsum dolor sit amet, image="150" consectetur adipisicing elit. Porro voluptatibus omnis nulla quis mollitia dicta quasi voluptatum totam,
labore doloremque ea fugit consectetur, itaque, ab et odio, est iusto recusandae suscipit? Dignissimos veniam recusandae, magnam, dolor omnis, image="6"
 eveniet laboriosam quas culpa voluptate at officia in natus repellendus assumenda beatae illo repudiandae earum necessitatibus fugit, 
quo error. <span style="padding-top:150px">Esse minima</span>, aut architecto, doloribus quos veritatis reprehenderit.
 Temporibus vitae voluptatibus ea ad similique perspiciatis sed doloribus explicabo error asperiores ab, id aspernatur image="235" eum ducimus magni rerum veniam voluptates, ipsum voluptatum repudiandae dolorum quisquam voluptatem. 
Doloribus nulla voluptate architecto ipsam sed voluptas, maiores rem sequi eos voluptatum iusto rerum odio sapiente sunt minima, image="65" consequuntur aliquid dolor impedit hic. Beatae perspiciatis, incidunt necessitatibus
 voluptas earum cumque, in asperiores id ipsum ducimus veritatis laboriosam eveniet ipsa accusamus! Nulla quasi porro sunt suscipit quibusdam velit
 itaque, voluptates, soluta quaerat consectetur eos doloribus, fugiat quisquam. Quos, ad, dolorum.
';

$array = array(
    '150' => 4025,
    '6'   => 4026,
    '235' => 4027,
    '65'  => 4028,
);

$find = array_keys($array);
foreach ($find as &$f) { $f = 'image="'.$f; }
$repl = array_values($array);
foreach ($repl as &$r) { $r = 'image="'.$r; }
print_r($find);print_r($repl);

$s1 = str_replace($find, $repl, $string);
echo $s1;

结果

Lorem ipsum dolor sit amet, image="4025" consectetur adipisicing elit. Porro voluptatibus omnis nulla quis mollitia dicta quasi voluptatum totam,
labore doloremque ea fugit consectetur, itaque, ab et odio, est iusto recusandae suscipit? Dignissimos veniam recusandae, magnam, dolor omnis, image="4026"
 eveniet laboriosam quas culpa voluptate at officia in natus repellendus assumenda beatae illo repudiandae earum necessitatibus fugit, 
quo error. <span style="padding-top:150px">Esse minima</span>, aut architecto, doloribus quos veritatis reprehenderit.
 Temporibus vitae voluptatibus ea ad similique perspiciatis sed doloribus explicabo error asperiores ab, id aspernatur image="4027" eum ducimus magni rerum veniam voluptates, ipsum voluptatum repudiandae dolorum quisquam voluptatem. 
Doloribus nulla voluptate architecto ipsam sed voluptas, maiores rem sequi eos voluptatum iusto rerum odio sapiente sunt minima, image="40265" consequuntur aliquid dolor impedit hic. Beatae perspiciatis, incidunt necessitatibus
 voluptas earum cumque, in asperiores id ipsum ducimus veritatis laboriosam eveniet ipsa accusamus! Nulla quasi porro sunt suscipit quibusdam velit
 itaque, voluptates, soluta quaerat consectetur eos doloribus, fugiat quisquam. Quos, ad, dolorum.

答案 2 :(得分:-1)

也许你可以用str_replace&amp;通过改变你的数组:

$string = 'Lorem ...';

$array = array(
    'image="150' => 'image="4025',
    'image="6'   => 'image="4026',
    'image="235' => 'image="4027',
    'image="65'  => 'image="4028',
);

$new_string = str_replace(array_keys($array), $array, $string);